You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 08:50:21