【问题标题】:Removing lines in a file that contain a certain word in python删除文件中包含python中某个单词的行
【发布时间】:2018-06-15 13:47:26
【问题描述】:

我的输入文件是这样的

car
dog
Rock

我试图编辑的输出文件如下所示。我的全部目标是删除所有包含单词 car 的行

cat car
sky rat
car cloud

这是我的初始代码,这里的问题是只有当它在这种情况下实际上只有“汽车”这个词时才会删除该行

from __future__ import print_function
import linecache
import fileinput

must_delete = linecache.getline('Test.txt', 1)

for line in fileinput.input('output.txt', inplace=True):
    if line != must_delete:
        print(line, end='')

【问题讨论】:

  • 由于'car''scary' 中,是否可以删除包含'scary' 的行? 'Car' 呢? 'Car''car' 应该被视为相等还是大小写重要?
  • @StevenRumbalski 我想说:使用if must_delete in line: .. 但你说得对
  • “可怕”不在文件或我的问题中
  • 我们不知道您的文件中有什么。 'card' 在您的文件中吗? 'carrot' 怎么样?我们可以在这上面走一整天。关键是要确定是否要进行全词匹配。您目前正在做整行匹配,需要细化,但具体如何细化是个问题。
  • Steven 正在提供一个边缘测试用例来正确定义预期行为。

标签: python arrays python-2.7 sorting


【解决方案1】:
from __future__ import print_function
import re
import linecache
import fileinput

must_delete = "car" # linecache.getline('Test.txt', 1)

text = '''
cat car g
sky rat
car cloud
scary thing
''' 

with open("cleaned_file.txt","w") as clean:
    for line in text.splitlines() :          # fileinput.input('output.txt', inplace=True):
        if  re.search(r"(\b"+must_delete+r"\b)", line, flags=re.IGNORECASE):
            print ("deleting line:"+ line)
        else:
            print ("this line has to be kept in the output: " + line)
            clean.write(line+"\n")

# cleaned_file.txt has all the needed lines

输出:

this line has to be kept in the output: 
deleting line:cat car g
this line has to be kept in the output: sky rat
deleting line:car cloud
this line has to be kept in the output: scary thing

我使用了一个正则表达式,其中包含您要删除的单词和两个单词边界,因此 car 必须是一个完整的单词。如果未找到正则表达式,re.search() 返回 None

正如 cmets 中所指出的,“可怕”也包含“汽车”——这就是简单的 if "car" in "scary": 不足以清除包含“汽车”但不是“汽车”的单词的原因。

【讨论】:

  • 我正在尝试打开一个文件并删除包含单词“car”的单词
  • 你在自相矛盾。上面您告诉我们您要“删除所有包含单词 car 的
  • 好的,在循环之前将must_delete小写,然后if must_delete in line.lower().split():
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-24
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 2016-03-01
相关资源
最近更新 更多