我有以下文本文件:
It’s hard to explain puns to kleptomaniacs because they always take things literally.
I used to think the brain was the most important organ. Then I thought, look what’s telling me that.
我使用以下脚本除去数字和换行符:
import re
with open('jokes.txt', 'r+') as original_file:
modfile = original_file.read()
modfile = re.sub("\d+\. ", "", modfile)
modfile = re.sub("\n", "", modfile)
original_file.seek(0)
original_file.truncate()
original_file.write(modfile)
运行脚本后,我的文本文件如下:
It’s hard to explain puns to kleptomaniacs because they always take things literally. I used to think the brain was the most important organ. Then I thought, look what’s telling me that.
我希望文件是:
It’s hard to explain puns to kleptomaniacs because they always take things literally.
I used to think the brain was the most important organ. Then I thought, look what’s telling me that.
如何删除新行而不修补所有行?你知道吗
可以使用一个替换,替换为以下正则表达式:
(?<!^)\n
将匹配换行符,除非它位于行的开头。标志re.MULTILINE
使^
匹配行的每个开头。你知道吗regex101 demo
在代码中:
如果需要,也可以使用负向前看而不是向后看:
相关问题 更多 >
编程相关推荐