gpt4 book ai didi

python - 替换单个换行符,保留倍数

转载 作者:行者123 更新时间:2023-12-03 22:34:23 26 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





replacing only single instances of a character with python regexp

(4 个回答)


4年前关闭。




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

这是我的第一首诗\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”而不是“helloworld”) .

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

最佳答案

您可以用空格替换所有未用其他换行符括起来的换行符:

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)

在这里, (?<!\n)如果换行符与另一个换行符一起后退,则是负向后视,匹配失败,并且 (?!\n)是一个否定的前瞻,它填充换行符的匹配,然后是另一个换行符。

查看更多关于 Lookahead and Lookbehind Zero-Length Assertions here .

关于python - 替换单个换行符,保留倍数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41241918/

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