在Python中使用正则表达式修改文件内容

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

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

我一直在尝试使用Python脚本删除下面几行中的数字。你知道吗

jokes.txt

  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.

当我运行这个Python脚本时:

import re
with open('jokes.txt', 'r+') as original_file:
    modfile = original_file.read()
    modfile = re.sub("\d+\. ", "", modfile)
    original_file.write(modfile)

数字仍然在那里,它被附加如下:

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

我猜正则表达式re.sub("\d+\. ", "", modfile)会找到0-9中的所有数字,并用空字符串替换它。你知道吗

作为一个新手,我不知道我把事情搞砸了。我想知道为什么会发生这种情况以及如何解决。你知道吗


Tags: thetoit数字alwaystakethingsthey
1条回答
网友
1楼 · 发布于 2024-09-28 03:23:24

您已经打开了文件进行读写,但在中读取文件后,您只需开始写入,而不指定要写入的位置。这会导致它从您停止读取的位置开始写入—在文件末尾。你知道吗

除了关闭文件并重新打开以进行写入之外,还有一种写入文件的方法:

import re
with open('jokes.txt', 'r+') as original_file:
    modfile = original_file.read()
    modfile = re.sub("\d+\. ", "", modfile)
    original_file.seek(0) # Return to start of file
    original_file.truncate() # Clear out the old contents
    original_file.write(modfile)

我不知道为什么数字还在你附加的部分,因为这对我来说很好。您可能希望在regex的开头添加插入符号(^)(结果是"^\d+\. ")。插入符号匹配一行的开头,这样如果你的一个笑话恰好在笑话中使用了1.之类的东西,那么开头的数字将被删除,而不是笑话中的数字。你知道吗

相关问题 更多 >

    热门问题