python - 如何查找字符串中重复单词的位置 - Python

标签 python

如何让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/

相关文章:

python - 将 matplotlib quiver 和 elipses 结合起来不起作用

python - 在 pyqt 的启动画面中使用 gif

python - 重用url请求方法

python - 使用 python 并行运行 n 个 MATLAB 实例

python - 无法理解 HTTP 请求处理函数如何访问 Tornado 中的应用程序对象

Python 扭曲 : Changing directories for each client independently

python - 动态添加group by子句到sql alchemy

Python 二叉树打印具有两个正好两个子节点的节点

java - 将 Python 字典迁移到 Java 和 JSON

python - 从一个字符串中提取多个子字符串