[英]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.