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

Python 是否查找列表中出现的所有单词?,python,list,loops,Python,List,Loops,我希望能够识别单词出现在句子中的所有位置 你好,我叫本,他叫弗雷德 如果我输入'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

我希望能够识别单词出现在句子中的所有位置

你好,我叫本,他叫弗雷德

如果我输入'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.')

这种理解应该做到:

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

这种理解应该做到:

[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以匹配预期索引

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])

您可以通过简单的列表理解和枚举函数来查找索引来实现这一点。最后添加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])

你不能用if来做这件事。必须有一个循环,如下所示:

occurrences = []

for word in sentence:
    if word == target_word:
        occurrences.append(sentence.index(word)+1)
您将拥有数组“事件”中的所有事件来打印您的句子,或者您可以根据自己的喜好更改“打印”句子的“事件”

请注意,我还没有运行这段代码,请检查它的拼写是否正确


祝你好运

你不能用if来做。必须有一个循环,如下所示:

occurrences = []

for word in sentence:
    if word == target_word:
        occurrences.append(sentence.index(word)+1)
您将拥有数组“事件”中的所有事件来打印您的句子,或者您可以根据自己的喜好更改“打印”句子的“事件”

请注意,我还没有运行这段代码,请检查它的拼写是否正确


祝你好运

这是一个重复的这是一个重复的我刚刚意识到这已经在这里得到了回答:谢谢,但在压缩中,我需要使用变量'word'作为字符串'name'的对应。这样用户就可以输入任何单词来查找匹配项?对。我编辑了我的答案来解决这个问题。我只是在一个简化的例子中测试了理解力,而不是整个代码。我刚刚意识到这里已经回答了这个问题:谢谢,但是在压缩过程中,我需要使用变量“word”作为字符串“name”的对应项。这样用户就可以输入任何单词来查找匹配项?对。我编辑了我的答案来解决这个问题。我只是在一个简化的例子中测试了理解力,而不是整个代码。是的,你可以做到。只需从用户处获取输入并将其存储为变量,然后就可以使用它进行比较。查看更正的代码。是的,您可以这样做。只需从用户处获取输入并将其存储为变量,然后就可以使用它进行比较。请参阅更正的代码。