Python实现删除含指定单词的整行及移除文件指定单词
解决文本文件行删除与单词替换问题
一、删除所有包含"pen"的整行
你的原代码逻辑搞反了——当前是把包含"pen"的行写回文件,而需求是排除这些行。修正后的代码如下:
with open("myfile.txt", "r") as f: lines = f.readlines() with open("myfile.txt", "w") as f: for line in lines: # 仅写入不包含"pen"的行 if "pen" not in line: f.write(line)
运行后文件内容会符合你的预期:
hi hello
二、仅删除文件中的"pen"单词
如果只想删除每行里的独立"pen"单词(保留该行其他内容,避免误删包含"pen"的复合词如"penholder"),可以用正则匹配独立单词来替换:
import re with open("myfile.txt", "r") as f: content = f.read() # \b 匹配单词边界,确保只替换独立的"pen" new_content = re.sub(r'\bpen\b', '', content) with open("myfile.txt", "w") as f: f.write(new_content)
处理后原文件内容会变为:
the is yellow is yellow hi hello
如果需要消除替换后留下的多余空格,可以再添加一行new_content = re.sub(r'\s+', ' ', new_content)来合并连续空格,根据自身格式需求选择即可。
内容的提问来源于stack exchange,提问作者user20793397
相关产品推荐
相关产品推荐

