2017-07-07 39 views
0

我目前拥有的代码可以删除包含一个特定字符串的文本文件中的所有行。这里是:如果行包含几个指定字符串之一,则从文本文件中删除行Python

import os 
with open(r"oldfile") as f, open(r"workfile", "w") as working:  
    for line in f: 
     if "string1" not in line: 
      working.write(line) 
os.remove(r"oldfile") 
os.rename(r"workfile", r"oldfile")  

我的问题是:我怎么能包括其他字符串?换句话说,我想告诉脚本,如果一行包含“string1”某个其他字符串“string2”,则删除该行。我知道我可以重复上面为每个这样的字符串提供的代码,但我确定有一些更简短更有效的方式来编写它。
非常感谢提前!

+0

这可能帮助:https://stackoverflow.com/ question/6531482/how-to-check-if-a-string-contains-an-element-from-a-list-in-python – yinnonsanders

回答

2

只是抽象出来成一个功能和使用?

def should_remove_line(line, stop_words): 
    return any([word in line for word in stop_words]) 

stop_words = ["string1", "string2"] 
with open(r"oldfile") as f, open(r"workfile", "w") as working:  
for line in f: 
    if not should_remove_line(line, stop_words): 
     working.write(line)  
0
if "string1" in line or "string2" in line: 

这应该工作,我觉得

+0

更新,是的,我尝试运行,它只能这样工作。根据OP需要检查的字符串数量,人们发布的涉及列表的其他一些方法可能会更好。 – J0hn

1

可能是很好的一个功能

def contains(list_of_strings_to_check,line): 
    for string in list_of_strings_to_check: 
    if string in line: 
     return False 
    return True 

list_of_strings = ["string1","string2",...] 
... 
for line in f: 
     if contains(list_of_strings,line): 
0

可以遍历你列入黑名单的字符串列表,同时保持跟踪,如果列入黑名单串之一是现在的这个样子:

import os 
blacklist = ["string1", "string2"] 
with open(r"oldfile") as f, open(r"workfile", "w") as working:  
    for line in f: 
     write = True 
     for string in blacklist: 
      if string in line: 
       write = False 
       break 
     if write: 
       working.write(line) 
os.remove(r"oldfile") 
os.rename(r"workfile", r"oldfile") 
相关问题