【发布时间】:2016-07-02 04:13:35
【问题描述】:
我正在从输入文件中读取行并将每一行拆分为列表。但是,我遇到了以下让我感到困惑的情况。
这是我的代码:
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' 等分隔符保留在结果中,但不希望将这个空元素 '' 保留。有没有办法做到这一点?
问题 Q1-2 的答案:here。
第三问的答案:here。
【问题讨论】:
-
但是为什么第一行没有这样的空字符串呢?
-
\s 匹配 \n 并用 (\s) 分割,会得到
'', \n, '',这是正常的 -
因为第一行不以\n开头?
-
第二行及以后的空白 '' 是因为缩进,也与 \s 匹配
标签: python regex string python-2.7