如何使用Python修改文本文件

2024-09-28 03:23:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下文本文件:

  1. It’s hard to explain puns to kleptomaniacs because they always take things literally.

  2. 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.

如何删除新行而不修补所有行?你知道吗


Tags: thetoitalwaysfiletakethingsoriginal
1条回答
网友
1楼 · 发布于 2024-09-28 03:23:44

可以使用一个替换,替换为以下正则表达式:

re.sub(r"\d+\. |(?<!^)\n", "", modfile, flags=re.MULTILINE)

(?<!^)\n将匹配换行符,除非它位于行的开头。标志re.MULTILINE使^匹配行的每个开头。你知道吗

regex101 demo

在代码中:

import re
with open('jokes.txt', 'r+') as original_file:
    modfile = original_file.read()
    midfile = re.sub(r"\d+\. |(?<!^)\n", "", modfile, flags=re.MULTILINE)
    original_file.seek(0)
    original_file.truncate()
    original_file.write(modfile)

如果需要,也可以使用负向前看而不是向后看:

r"\d+\. |\n(?!\n)"

相关问题 更多 >

    热门问题