gpt4 book ai didi

python - 当单词不在句子中时无法让程序打印 "not in sentence"

转载 作者:太空宇宙 更新时间:2023-11-04 07:17:01 25 4
gpt4 key购买 nike

我有一个程序要求输入一个句子,然后要求输入一个词,并告诉你那个词的位置:

sentence = input("enter sentence: ").lower()
askedword = input("enter word to locate position: ").lower()
words = sentence.split(" ")

for i, word in enumerate(words):
if askedword == word :
print(i+1)
#elif keyword != words :
#print ("this not")

但是,当我编辑程序时,如果输入的单词不在句子中,则打印“this isn't in the sentence”,我无法让程序正常工作

最佳答案

列表是序列,因此您可以使用 the in operation在它们上测试 words 列表中的成员资格。如果在里面,用words.index找到句子里面的位置:

sentence = input("enter sentence: ").lower()
askedword = input("enter word to locate position: ").lower()
words = sentence.split(" ")

if askedword in words:
print('Position of word: ', words.index(askedword))
else:
print("Word is not in the given sentence.")

带有示例输入:

enter sentence: hello world

enter word to locate position: world
Position of word: 1

并且,一个错误的案例:

enter sentence: hello world

enter word to locate position: worldz
Word is not in the given sentence.

如果您要检查多个匹配项,那么使用 enumerate 的列表理解是可行的方法:

r = [i for i, j in enumerate(words, start=1) if j == askedword]

然后检查列表是否为空并相应地打印:

if r:
print("Positions of word:", *r)
else:
print("Word is not in the given sentence.")

关于python - 当单词不在句子中时无法让程序打印 "not in sentence",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39579770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com