用字典在 Python 中找到字符串中的第一个重复单词
在给定的句子中可能有一个单词在句子结束前重复出现。在这个 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP