我正在解析一个文本文件,并希望删除所有段落内换行符,同时实际上保留形成新段落的双换行符。例如
这是我的第一首诗\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”而不是“helloworld”) 。
我可以通过首先用虚拟字符串替换 \n\n 来做到这一点(例如“$$$”,或者同样荒谬的东西),然后删除 \n,然后重新转换“$$$" 回到 \n\n...但这似乎过于迂回。我可以通过单个正则表达式调用来进行此转换吗?
您可以用空格替换所有未用其他换行符括起来的换行符:
re.sub(r"(?<!\n)\n(?!\n)", " ", s)
See the Python演示:
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)
在这里,(?<!\n)
is a 消极回顾如果换行符与另一个换行符一起退出,则匹配失败,并且(?!\n)
is a 负前瞻fils 换行符的匹配后面跟着另一个换行符。
查看更多关于前向和后向零长度断言 here.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)