如何打印包含特定字母的单词

我有单词文件,每行包含一个单词。我尝试做的是向用户询问字母并搜索用户输入的所有这些字母的单词。我研究了几天,但无法使第 7 行和第 8 行正常运行,只会出现不同的错误,或者两者都没有给出任何结果。


letters = input('letters: ')

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


print (words)

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


for word in words:

    if all(letters) in word:

        print(word)


慕容708150
浏览 127回答 4
4回答

收到一只叮咚

你用all()错了。 all(letters)始终是一个Truefor string letters,并True in <string>返回一个TypeError.你应该做的是:all(x in word for x in letters)于是,就变成了:for word in words:&nbsp; &nbsp; if all(x in word for x in letters):&nbsp; &nbsp; &nbsp; &nbsp; print(word)

梵蒂冈之花

由于代码中有很多语法错误,我正在尝试重写您提供的代码,以粗略地描绘出您的目标。我希望下面的代码能够满足您的需求。letters = input("letters:" )words = open("thesewords.txt","r")for word in line.split():&nbsp; &nbsp; print (word)print(".......................")for wrd in words:&nbsp; &nbsp; if letters in wrd:&nbsp; &nbsp; &nbsp; &nbsp; print(wrd)&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; continue

繁星淼淼

如果您省略,则更简单的解决方案all是:letters = input('letters: ')words_in_file = open('thesewords').read().splitlines()for word in words_in_file:&nbsp; &nbsp; if letters in words:&nbsp; &nbsp; &nbsp; &nbsp; 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:&nbsp; &nbsp; if all(x in word for x in letters):&nbsp; &nbsp; &nbsp; &nbsp; print(word)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python