簡體   English   中英

刪除包含特定字符串的行

[英]Remove lines containing specific strings

我正在嘗試編寫一個函數來刪除 Python 文本文件中包含特定字符串的所有行,雖然我能夠編寫一個函數,但它並沒有做我想要的。 當我打開文件並讀取行時,它要么給我原始文件,要么根本沒有行。

以下是我嘗試過的幾種替代方案:

bads = ['IV\t', '', 'Speaker Key:\n', 'Page 1 of 1\n']
string_bads = str(bads)

def prepText(file):
    with open(file, 'w+') as textfile:
        for line in textfile: 
            if not string_bads in line:
                pass
            else:
                textfile.write(line)   


def prepText(file):
    with open(file, 'w+') as textfile:
        for line in textfile: 
            if not string_bads in line:
                pass
            else:
                textfile.write(line)

def prepText(file):
    with open(file, 'w') as textfile:
        for line in textfile:
            if line.strip("\n") != string_bads:
               textfile.write(line)

def prepText(file1, file2):
     with open(file1) as oldfile, open(file2, 'w') as newfile:
         for line in oldfile:
             if not any(string_bads in line for bads in string_bads):
               newfile.write(line)

之后,我只是將文件傳遞給函數,一旦完成,我會這樣做:

with open("newfile") as good_one:
    lines = good_one.readlines()
print(lines)
lines

你在這里有一個大問題:

bads = ['IV\t', '', 'Speaker Key:\n', 'Page 1 of 1\n']
string_bads = str(bads)

因為您的string_bads將是:

"['IV\\t', '', 'Speaker Key:\\n', 'Page 1 of 1\\n']"

如果要檢查文件中的每一行是否包含一個或多個bads字符串,則應如下所示:

def prepText(file1, file2):
     with open(file1) as oldfile, open(file2, 'w') as newfile:
         for line in oldfile:
             if not any(bad in line for bad in bads):
               newfile.write(line)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM