亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

慕容708150 2023-05-23 10:29:06
我有單詞文件,每行包含一個單詞。我嘗試做的是向用戶詢問字母并搜索用戶輸入的所有這些字母的單詞。我研究了幾天,但無法使第 7 行和第 8 行正常運行,只會出現不同的錯誤,或者兩者都沒有給出任何結果。letters = input('letters: ')words = open('thesewords').read().splitlines()print (words)print(".......................")for word in words:    if all(letters) in word:        print(word)
查看完整描述

4 回答

?
收到一只叮咚

TA貢獻1821條經驗 獲得超5個贊

你用all()錯了。 all(letters)始終是一個Truefor string letters,并True in <string>返回一個TypeError.


你應該做的是:


all(x in word for x in letters)

于是,就變成了:


for word in words:

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

        print(word)


查看完整回答
反對 回復 2023-05-23
?
梵蒂岡之花

TA貢獻1900條經驗 獲得超5個贊

由于代碼中有很多語法錯誤,我正在嘗試重寫您提供的代碼,以粗略地描繪出您的目標。我希望下面的代碼能夠滿足您的需求。


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


查看完整回答
反對 回復 2023-05-23
?
繁星淼淼

TA貢獻1775條經驗 獲得超11個贊

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


letters = input('letters: ')

words_in_file = open('thesewords').read().splitlines()


for word in words_in_file:

    if letters in words:

        print(word)


查看完整回答
反對 回復 2023-05-23
?
一只斗牛犬

TA貢獻1784條經驗 獲得超2個贊

嘗試這個:


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)


查看完整回答
反對 回復 2023-05-23
  • 4 回答
  • 0 關注
  • 228 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號