簡體   English   中英

Python - 刪除列表中所有以單詞/字符串開頭的行

[英]Python - Remove all the lines starting with word/string present in a list

我正在嘗試解析巨大的 50K 行文件,其中我必須刪除以預定義列表中存在的單詞開頭的任何行。

目前,我已經嘗試了以下操作,但輸出文件 (DB12_NEW) 無法正常工作 -

rem = ['remove', 'remove1', 'remove2'....., 'removen']

inputFile = open(r"C:\file", "r")
outputFile = open(r"C:\file_12", "w")
lines = inputFile.readlines()
inputFile.close()
for line in lines:
    for i in rem:
        if line.startswith(i):
            outputFile.write('\n')
        else:
            outputFile.write(line)

我得到的文件與我最初輸入的輸出相同......腳本沒有刪除以列表中存在的任何字符串開頭的行。

你能幫助理解如何實現這一目標嗎?

str.startswith使用tuple而不是list

# rem = ['remove', 'rem-ove', 'rem ove']
rem = ('remove', 'rem-ove', 'rem ove')

with open('DB12', 'r') as inputFile, open('DB12_NEW', 'w') as outputFile:
    for line in inputFile.readlines():
        if not line.startswith(rem):
            outputFile.writelines(line)

當前,您一次檢查該行是否以刪除列表中的一個單詞開頭。 例如:

如果該行以“rem ABCDF...”開頭,並且在您的循環中檢查該行是否以“remove”開頭,則您的 if 語句返回 false 並將該行寫入輸出文件。

你可以嘗試這樣的事情:

remove = ['remove', 'rem-ove', 'rem', 'rem ove' ...... 'n']
inputFile = open(r"C:\DB12", "r")
outputFile = open(r"C:\DB12_NEW", "w")
for line in inputFile.splitlines():
    if not any(line.startswith(i) for i in remove):
        outputFile.write(line)

any關鍵字只返回False ,如果所有元素也False

有時這可能是由前導/尾隨空格引起的。

嘗試使用strip()去除空白區域並檢查。

rem = [x.strip() for x in rem]
lines = [line.strip() for  line in lines]

暫無
暫無

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

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