我正在讀取輸入文件中的行並將每行分割爲列表。但是,我遇到了以下困惑我的情況。什麼是拆分後我的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。
[*如果在分隔符中有捕獲組,並且它在字符串的開頭匹配,則結果將以空字符串開頭。這同樣適用於字符串*](https://docs.python.org/2/library/re.html#re.split) –
的末尾。但爲什麼第一行沒有這樣的空字符串? – fluency03
\ s match \ n並用(\ s)分割,會得到''',\ n,''',這是正常的 – YOU