2016-03-16 26 views
3

我正在讀取輸入文件中的行並將每行分割爲列表。但是,我遇到了以下困惑我的情況。什麼是拆分後我的readline()的空字符串

這是我的代碼:

with open("filename") as in_file: 
    for line in in_file: 
     print re.split(r'([\s,:()\[\]=|/\\{}\'\"<>]+)', line) 

這是我的輸入文件的演示:

PREREQUISITES 

    CUDA 7.0 and a GPU of compute capability 3.0 or higher are required. 


    Extract the cuDNN archive to a directory of your choice, referred to below as <installpath>. 
    Then follow the platform-specific instructions as follows. 

這是輸出結果我:

['PREREQUISITES', '\n', ''] 
['', '\n', ''] 
['', ' ', 'CUDA', ' ', '7.0', ' ', 'and', ' ', 'a', ' ', 'GPU', ' ', 'of', ' ', 'compute', ' ', 'capability', ' ', '3.0', ' ', 'or', ' ', 'higher', ' ', 'are', ' ', 'required.', '\n', ''] 
['', '\n', ''] 
['', '\n', ''] 
['', ' ', 'Extract', ' ', 'the', ' ', 'cuDNN', ' ', 'archive', ' ', 'to', ' ', 'a', ' ', 'directory', ' ', 'of', ' ', 'your', ' ', 'choice', ', ', 'referred', ' ', 'to', ' ', 'below', ' ', 'as', ' <', 'installpath', '>', '.', '\n', ''] 
['', ' ', 'Then', ' ', 'follow', ' ', 'the', ' ', 'platform-specific', ' ', 'instructions', ' ', 'as', ' ', 'follows.', '\n', ''] 

我的問題是:

Q1:在每行的末尾,除字符\n之外,還有另一個空元素''。那是什麼? Q2:第一個,所有其他行的內容都以此空元素''開頭。這是爲什麼?

編輯:

問題補充Q3:我想要的分隔符,如' ''\n'保持在結果而不是這個空emement ''。有沒有辦法做到這一點?

對問題Q1-2的回答:here

對問題Q3的回答:here

+2

[*如果在分隔符中有捕獲組,並且它在字符串的開頭匹配,則結果將以空字符串開頭。這同樣適用於字符串*](https://docs.python.org/2/library/re.html#re.split) –

+0

的末尾。但爲什麼第一行沒有這樣的空字符串? – fluency03

+0

\ s match \ n並用(\ s)分割,會得到''',\ n,''',這是正常的 – YOU

回答

1

空字符串表示'\n'被匹配爲行中的最後一個字符,並且後面沒有更多數據。那就是:

>>> re.split(r'([\s]+)', 'hello world\n') 
['hello', ' ', 'world', '\n', ''] 

應該產生不同的結果:

>>> re.split(r'([\s]+)', 'hello world') 
['hello', ' ', 'world'] 

您可以拆分它之前剝去線:

>>> re.split(r'([\s]+)', 'hello world\n'.strip()) 
['hello', ' ', 'world'] 

或反轉的正則表達式,並使用findall代替。 findall將工作不同,因爲它不會產生匹配文本之間的序列。

>>> re.findall(r'([^\s]+)', 'hello world\n') 
['hello', 'world'] 
+0

我想要匹配的文本('split'中的分隔符),比如''''和''\ n'',但不是這個空白的''''''。有沒有辦法做到這一點? – fluency03