简体   繁体   English

查找列表中所有出现的单词?

[英]Find all occurrences of a word in a list?

I want to be able to identify all of the positions where a word appears in a sentence. 我希望能够识别单词在句子中出现的所有位置。

For example: Hello my name is Ben and his name is Fred. 例如:您好,我叫Ben,名字叫Fred。

If I input 'name' it should return: This word occurs in the places: 3 and 8 如果输入“名称”,则应返回:此单词出现在以下位置:3和8

Below is my code however it will only return the first value. 下面是我的代码,但是它只会返回第一个值。

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.')

This comprehension should do it: 这种理解应该做到:

[i+1 for i, w in enumerate(sentence) if w == word]

(+1 because you want first word to be 1 not 0) (+1,因为您希望第一个单词为1而不是0)

Full example: 完整示例:

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.')

You can achieve this with simple list comprehension and enumerate function to find the index. 您可以通过简单的列表理解和枚举函数来找到索引来实现这一点。 Finally add 1 to match your expected index. 最后加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])

You cannot do it with an if. 您无法使用if做到这一点。 You must have one loop, like this: 您必须有一个循环,如下所示:

occurrences = []

for word in sentence:
    if word == target_word:
        occurrences.append(sentence.index(word)+1)

You will have all the occurrences in the array 'occurrences' to print your sentence or you can change 'occurrences' for a 'print' sentence, as your preference. 您可以将数组“出现次数”中的所有出现次数都打印出来,也可以根据自己的喜好更改“打印”句子的“出现次数”。

Please, note that I hasn't run this code, check if it is correct spelled. 请注意,我尚未运行此代码,请检查其拼写是否正确。

Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM