2016-02-18 38 views
0

我读过了本网站上的其他线程,但还没有完全掌握如何完成我想要做的事情。我想找到像.splitlines()这样的方法将多行字符串中的前两行文本分配到两个单独的变量中。然后将字符串中的其余文本分组在另一个变量中。Python .splitlines()将文本分割成单独的变量

其目的是使用一致的数据集将三个变量作为独立列的数据写入.csv。

Title of a string  
Description of the string   

There are multiple lines under the second line in the string! 
There are multiple lines under the second line in the string! 
There are multiple lines under the second line in the string! 

任何指导pythonic的方式来做到这一点,将不胜感激。

回答

1

使用islice

除了正常的列表切片可以使用islice()产生大名单的切片时,这是更好的性能。

代码应该是这样的:

from itertools import islice 

with open('input.txt') as f: 
    data = f.readlines() 


first_line_list = list(islice(data, 0, 1)) 
second_line_list = list(islice(data, 1, 2)) 
other_lines_list = list(islice(data, 2, None)) 

first_line_string = "".join(first_line_list) 
second_line_string = "".join(second_line_list) 
other_lines_string = "".join(other_lines_list) 

然而,你应该记住,你从中读取数据源是足够长的时间。如果不是,则在使用正常列表切片时,使用islice()IndexError时会引起StopIteration错误。


使用正则表达式

的OP要求另外在下面的评论列表少的方法。 由于从文件读取数据导致字符串,并通过字符串处理后来列表或直接到我建议使用正则表达式的读取行列表。

我不能告诉任何有关列表/字符串处理和正则表达式操作之间的性能比较。然而,这应该做的工作:

import re 

regex = '(?P<first>.+)(\n)(?P<second>.+)([\n]{2})(?P<rest>.+[\n])' 

preg = re.compile(regex) 

with open('input.txt') as f: 
    data = f.read() 

match = re.search(regex, data, re.MULTILINE | re.DOTALL) 

first_line = match.group('first') 
second_line = match.group('second') 
rest_lines = match.group('rest') 
+0

这看起来如果我正在处理多行字符串,有没有办法避免必须创建一个列表,然后加入所述列表? – ImNotLeet

+0

我没有看到避免列表的任何理由,因为这些是Python中非常基本的数据类型,并且在大多数情况下它们的实现速度足够快。我可以考虑的不使用列表的唯一方法是使用正则表达式与匹配组,这将是一种讨厌... – albert

+1

@ImNotLeet:请参阅使用正则表达式更新。 – albert

1

如果我理解正确的,你想一个大的字符串分割成线

lines = input_string.splitlines() 

之后,你要分配的第一和第二行的变量,其余的另一个变量

title = lines[0] 
description = lines[1] 
rest = lines[2:] 

如果你想'休息'是一个字符串,你可以通过加入换行符来实现。

rest = '\n'.join(lines[2:]) 

不同的,非常快速的选择是:

lines = input_string.split('\n', maxsplit=2) # This only separates the first to lines 
title = lines[0] 
description = lines[1] 
rest = lines[2] 
+0

该OP想要保存标题和说明在一个单一的多行字符串。 另外,'rest'将返回一个列表。 – leongold

相关问题