【问题标题】:Python regex to match one or more line breaks? [duplicate]Python正则表达式匹配一个或多个换行符? [复制]
【发布时间】:2020-07-27 15:03:44
【问题描述】:

我想将一个文本文件分成多个段落,用 1 个或多个空行分隔。 例如:

# file.txt
"Paragraph1
Some text

Paragraph2
More text

Paragraph3
some more text"

我尝试使用正则表达式,但我不确定我是否正确使用。在示例中,我仅尝试打印第二段,但出现list index out of range 错误。但是当我打印p[0] 时,它会打印整个文本文件。我究竟做错了什么?我应该使用不同的正则表达式吗?或者其他方法将文件分成段落?

with open(file) as f:
    text = f.read()

p = text.split("[\r\n]+")
print(p[1])

【问题讨论】:

  • 您拥有的+[] 是正则表达式元字符。 Python 的常规 str.split() 不接受正则表达式参数。
  • 啊,我明白了,那么看起来 "\n\n" 应该可以工作
  • *似乎 "\n\n" 应该可以工作 * 正确。

标签: python regex split


【解决方案1】:

使用re.split()

>>> import re
>>> re.split(r'[\r\n][\r\n]+', text)
['Paragraph1\nSome text', 'Pragraph2\nMore text', 'Paragraph3\nsome more text']

【讨论】:

    【解决方案2】:

    你有一个错误,因为你没有分割你的文本(因此,没有第二个元素),你可以使用这个分隔符:

    p = text.split("\n\n")
    

    【讨论】:

      【解决方案3】:

      尝试使用下面的文本在文本中添加一个空格。

      重新导入

      fin = open("data.txt", "rt") fout = open("out.txt", "wt")

      对于 fin 中的行: fout.write(re.sub('\s+',' ',line))

      fin.close() fout.close()

      【讨论】:

        猜你喜欢
        • 2013-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多