【问题标题】:Replace single line-feed characters, keep multiples [duplicate]替换单个换行符,保留多个[重复]
【发布时间】:2017-05-05 15:29:50
【问题描述】:

我正在解析一个文本文件,并希望删除所有段落内换行符,同时实际上保留形成新段落的双换行符。例如

这是我的第一首诗\n没有意义\n应该走多远\n没人知道。\n\n这是一秒钟\n没那么长\n再见\n\n

打印出来后应该是这样的:

This is my first poem
that does not make sense
how far should it go
nobody can know.

Here is a seconds
that is not as long
goodbye

应该变成

这是我的第一首没有意义的诗,它应该走多远没人知道。\n\n这是一秒不那么长的再见\n\n

同样,当打印出来时,它应该是这样的:

This is my first poem that does not make sense how far should it go nobody can know.

Here is a seconds that is not as long goodbye

这里的技巧是删除单个出现的 '\n',同时保留双换行符 '\n\n',并保留空白(即“hello\nworld”变为“hello world”而不是“你好世界”)。

我可以先用一个虚拟字符串(如“$$$”或同样荒谬的东西)替换 \n\n,然后删除\n 然后将 "$$$" 重新转换回 \n\n...但这似乎过于迂回。我可以通过单个正则表达式调用进行此转换吗?

【问题讨论】:

    标签: python regex python-3.x


    【解决方案1】:

    您可以用空格替换所有未包含在其他换行符中的换行符:

    re.sub(r"(?<!\n)\n(?!\n)", " ", s)
    

    Python demo

    import re
    s = "This is my first poem\nthat does not make sense\nhow far should it go\nnobody can know.\n\nHere is a seconds\nthat is not as long\ngoodbye\n\n"
    res = re.sub(r"(?<!\n)\n(?!\n)", " ", s)
    print(res)
    

    这里,(?&lt;!\n)negative lookbehind 如果换行符被另一个换行符后退则匹配失败,(?!\n)negative lookahead换行符的匹配后面跟着另一个换行符。

    查看更多关于Lookahead and Lookbehind Zero-Length Assertions here的信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-12
      • 2012-05-14
      • 2011-05-02
      • 1970-01-01
      • 2015-10-28
      相关资源
      最近更新 更多