如何让Python返回字符串中重复单词的位置?
例如“the cat sat on the mat which was lower the cat”中的“cat”一词位于句子中的第 2 和第 11 个位置。
最佳答案
您可以使用re.finditer
查找字符串中该单词的所有出现位置和起始索引:
import re
for word in set(sentence.split()):
indexes = [w.start() for w in re.finditer(word, sentence)]
print(word, len(indexes), indexes)
并使用字典理解:
{word: [w.start() for w in re.finditer(word, sentence)] for word in sentence.split()}
关于python - 如何查找字符串中重复单词的位置 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35209466/