gpt4 book ai didi

python - 拆分后我的 readline() 的空字符串是什么

转载 作者:行者123 更新时间:2023-11-28 18:32:05 24 4
gpt4 key购买 nike

我正在从输入文件中读取行并将每一行拆分为列表。然而,我遇到了下面的情况,让我很困惑。

这是我的代码:

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 .

最佳答案

空字符串表示 '\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']

关于python - 拆分后我的 readline() 的空字符串是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36033021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com