2016-02-18 39 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

相關問題