如何让python重新注册列表和返回位置中的相同字符串

如何让python重新注册列表和返回位置中的相同字符串,python,arrays,string,list,return,Python,Arrays,String,List,Return,我有一个句子单词,当该句子中的一个单词作为“查找该单词”功能输入时,程序会识别该单词出现在句子中的所有位置并返回结果 如果判决是: I wish upon a star and the star wishes upon me 我想找到这个词,结果是 the word "upon" is in position: 1 and 9 这句话不区分大小写,所以前后都是一样的。用户也可以输入句子 有没有关于如何编码的想法?一种方法是枚举列表。对照关键字检查值,然后保留索引 import re def

我有一个句子单词,当该句子中的一个单词作为“查找该单词”功能输入时,程序会识别该单词出现在句子中的所有位置并返回结果

如果判决是:

I wish upon a star and the star wishes upon me
我想找到这个词,结果是

the word "upon" is in position: 1 and 9
这句话不区分大小写,所以前后都是一样的。用户也可以输入句子


有没有关于如何编码的想法?

一种方法是
枚举列表。对照关键字检查值,然后保留索引

import re

def find_dup(sentence, keyword):
    keyword = keyword.lower()
    words = re.sub('[^\w]', ' ', sentence.lower()).split()
    return [index for index, value in enumerate(words) if value == keyword]

sentence = 'I wish upon a star and the star wishes upon me. Upon capital.'
keyword = 'upon'
positions = find_dup(sentence, keyword)
print positions
print 'the word "{}" is in position: {}'.format(keyword, ' '.join([str(p) for p in positions]))
输出:

[2, 9, 11]
the word "upon" is in position: 2 9 11

可能是
2和9
而不是
1和9
?到目前为止你试过什么?如果关键字出现两次以上,您将如何显示输出?这是一个用于此任务的函数:
find_word=lambda语句,needle:[索引的索引,枚举中的单词(map(str.lower,句子.split()))如果word==needle.lower()][/code>。现在去跟你的老师解释一下。@XinHuang如果关键词出现两次以上,它应该只是打印出位置,所以如果我有一个1000字的句子,并且关键词出现了多次,它会返回单词的位置,不管单词出现多少次。我也尝试过使用“list.index”,但当关键字出现多次时,它不能正确返回该单词。有什么想法吗?@D.Forrester,list.index只返回第一次出现的代码。我发布的代码可以工作,但显然你的Python知识还处于初级水平。你知道如何把字符串分成不同的单词吗?如果没有,请阅读,你会找到一个方法。