簡體   English   中英

如何打印包含特定字母的單詞

[英]How to print words containing specific letters

我有單詞文件,每行包含一個單詞。 我嘗試做的是向用戶詢問字母並搜索用戶輸入的所有這些字母的單詞。 我工作了幾天,但無法使第 7 行和第 8 行正常運行,只會出現不同的錯誤,或者沒有給出任何結果。

letters = input('letters: ')
words = open('thesewords').read().splitlines()

print (words)
print(".......................")

for word in words:
    if all(letters) in word:
        print(word)

您錯誤地使用all() all(letters)對於字符串letters始終是True ,而True in <string>的 True 會返回TypeError

你應該做的是:

all(x in word for x in letters)

所以,它變成:

for word in words:
    if all(x in word for x in letters):
        print(word)

如果您省略all ,則更簡單的解決方案是:

letters = input('letters: ')
words_in_file = open('thesewords').read().splitlines()

for word in words_in_file:
    if letters in words:
        print(word)

嘗試這個:

letters = input('letters: ')

# Make sure you include the full file name and close the string
# Also, .readlines() is simpler than .read().splitlines()
words = open('thesewords.txt').readlines()

# I'll assume these are the words:
words = ['spam', 'eggs', 'cheese', 'foo', 'bar']

print(words)
print(".......................")

for word in words:
    if all(x in word for x in letters):
        print(word)

由於代碼中有很多語法錯誤,我正在嘗試重新編寫您提供的代碼,繪制您的目標的粗略草圖。 我希望下面的代碼能滿足您的需求。

letters = input("letters:" )
words = open("thesewords.txt","r")
for word in line.split():
    print (word)
print(".......................")
for wrd in words:
    if letters in wrd:
        print(wrd)
    else:
        continue

暫無
暫無

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

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