簡體   English   中英

PYTHON如何檢查某行是否包含特定字母,以及是否不打印該行

[英]PYTHON How to check if a line contains specific letters and if not print the line

我有一個包含大量數據的文本文件。我試圖逐行讀取文件,並檢查每行中是否有任何字母是單詞“ hello”中的字母。

然后我想打印任何不包含h,e,l,l,o的行

我的文本文件稱為data.txt

到目前為止,這里有更多代碼:

hello = list('hello')
with open('data.txt', 'r') as file.readlines:
    for line in file:
        if hello not in line:
            print(line)

但目前第3行產生了錯誤; NameError:名稱“文件”未定義

更新:

hello = list('hello')
with open('data.txt', 'r') as f:
    for line in f:
        s = set(line)
        if all(i not in s for i in hello):
            print(line)

謝謝您的幫助,現在文本文件的許多行都已被刪除,但是仍然打印“ Epping”,其中帶有“ e”,單詞“ hello”也一樣,因此應該排除它嗎?

您打開文件錯誤。

hello = list('hello')
with open('data.txt', 'r') as f:
    for line in f:
        s = set(line)
        if all(letter not in s for letter in hello):
            print(line)

這不是“ with”的正確用法。 嘗試這個:

with open('<filename>') as f:
    for line in f:
        ...

如果您只想顯示其中任何一個字母(不是全部),則可以使用設置交集:

hello_set = set('hello')
for line in f:
    if not set(line).intersection(hello_set):
        print line

或使用“任何”功能:

for line in f:
    s = set(line)
    if any(letter not in s for letter in hello):
        print(line)

您的代碼中有幾個小錯誤。 我修復了它們,請比較。

hello = list('hello')
with open('data.txt', 'r') as file:
    for line in file:
      if all(letter not in line for letter in "hello"):
            print(line)

暫無
暫無

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

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