我从输入文件中读取行,并将每一行拆分为列表。然而,我遇到了以下情况,使我感到困惑。
这是我的密码:
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 ''。有办法这样做吗?
问题1-2:here的回答.
对Q3问题的回答:here。
发布于 2016-03-16 11:45:22
空字符串表示'\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']https://stackoverflow.com/questions/36033021
复制相似问题