我希望能够识别句子中出现单词的所有位置。
例如:您好,我的名字是本,他的名字是弗雷德。
如果我输入' name'它应该返回:这个词出现在地方:3和8
以下是我的代码,但它只会返回第一个值。
text = input('Please type your sentence: ')
sentence = text.split()
word= input('Thank-you, now type your word: ')
if word in sentence:
print ('This word occurs in the places:', sentence.index(word)+1)
elif word not in sentence:
print ('Sorry, '+word+' does not appear in the sentence.')
答案 0 :(得分:2)
这种理解应该这样做:
[i+1 for i, w in enumerate(sentence) if w == word]
(+ 1因为你想要第一个单词是1而不是0)
完整示例:
text = input('Please type your sentence: ')
sentence = text.split()
word = input('Thank-you, now type your word: ')
if word in sentence:
print ('This word occurs in the places:')
print([i+1 for i, w in enumerate(sentence) if w == word])
elif word not in sentence:
print ('Sorry, ' + word + ' does not appear in the sentence.')
答案 1 :(得分:1)
您可以通过简单的列表理解和枚举函数来实现此目的,以查找索引。最后加1以匹配您的预期指数。
sec = 'Hello my name is Ben and his name is Fred.'
search = input('What are you looking for? ')
print ([i + 1 for i, s in enumerate(sec.split()) if s == search])
答案 2 :(得分:0)
你不能用if做。你必须有一个循环,如下所示:
occurrences = []
for word in sentence:
if word == target_word:
occurrences.append(sentence.index(word)+1)
您将在阵列中发生所有事件'出现'打印你的句子,或者你可以改变发生的事件'打印'打印'句子,作为你的偏好。
请注意,我没有运行此代码,请检查拼写是否正确。
祝你好运!