为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕容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条经验 获得超4个赞

你用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 关注
  • 119 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信