使用 Python 字典查找字符串中的第一个重复单词
pythonserver side programmingprogramming
在给定的句子中,可能有一个单词在句子结束前重复出现。在这个 Python 程序中,我们将捕捉句子中重复出现的单词。下面是我们将遵循的逻辑步骤来获得此结果。
- 将给定的字符串拆分为以空格分隔的单词。
- 然后我们使用集合将这些单词转换为字典
- 遍历这个单词列表并检查哪个第一个单词的频率 > 1
程序 - 查找重复的单词
在下面的程序中,我们使用集合包中的计数器方法来保持单词的数量。
示例
from collections import Counter def Repeat_word(load): word = load.split(' ') dict = Counter(word) for value in word: if dict[value]>1: print (value) return if __name__ == "__main__": input = 'In good time in bad time friends are friends' Repeat_word(input)
运行上述代码得到以下结果 −
输出
time