簡體   English   中英

在文本文件Python中搜索字母

[英]Search letters in a text file Python

我想知道是否有人可以幫助我。 我是Python的初學者。 我想要做的是鍵入任何字母,程序必須在帶有對象列表的文本文件中找到它們。 它必須打印包含所有字母的對象,而沒有特定順序。 例如,我有一個包含5個單詞的文本文件:

yellow
morning
sea
soiberg
sand

我希望程序顯示所有包含字母"goi"的單詞。

結果:

morning
soiberg

我現在所擁有的是:

with open('d:\lista.txt', 'r') as inF:
   l = input("Buscar: ")
   for line in inF:
       if l[0] in line:
          if l[1] in line:
              if l[2] in line:
                 print(line)

但是,如果我只想找到2個字母或5或7個字母,該怎么辦?我不知道該怎么辦

您可以使用all()

with open(r'd:\lista.txt', 'r') as inF:
    l = input("Buscar: ")
    for line in inF:
        if all(c in line for c in l)
          #code

例子:

>>> strs = "goi"
>>> line = "morning"
>>> all(c in line for c in strs)
True
>>> line = "soiberg"
>>> all(c in line for c in strs)
True
>>> line = "sea"
>>> all(c in line for c in strs)
False

請注意,對於Windows文件路徑,應使用原始字符串,否則文件路徑中的'\\t'之類的內容將轉換為制表符空間,並且會出現錯誤。

r'd:\lista.txt'

我會去使用一個集合,並在匹配行上構建一個生成器,然后對其進行迭代:

with open('input') as fin:
    letters = set(raw_input('Buscar: '))
    matches = (line for line in fin if not letters.difference(line.strip())
    for match in matches:
        # do something

這是使用簡單工具的另一種方法:

with open(r'd:\lista.txt', 'r') as inF:
    l = input("Buscar: ")
    for line in inF:
        counter=0
        for letter in l:
            if letter in line:
                counter+=1
        if counter==len(l):
            print(line)

暫無
暫無

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

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