2017-07-07 74 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") 
相關問題