【问题标题】:What are the empty strings of my readline() after split拆分后我的 readline() 的空字符串是什么
【发布时间】: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

【问题讨论】:

标签: python regex string python-2.7


【解决方案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']

或者反转正则表达式并改用findallfindall 的工作方式不同,因为它不会在匹配文本之间产生序列。

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

【讨论】:

  • 我想要匹配的文本(split 中的分隔符),例如 ' ''\n',但不是这个空元素 ''。有没有办法做到这一点?
猜你喜欢
  • 1970-01-01
  • 2017-06-18
  • 2011-12-29
  • 1970-01-01
  • 1970-01-01
  • 2012-02-14
  • 2014-11-27
  • 2011-06-25
  • 1970-01-01
相关资源
最近更新 更多