📌  相关文章
📜  在Python中使用 Dictionary 查找字符串中第一个重复的单词

📅  最后修改于: 2022-05-13 01:54:45.159000             🧑  作者: Mango

在Python中使用 Dictionary 查找字符串中第一个重复的单词

先决条件:字典数据结构

给定一个字符串,找出字符串中第一个重复的单词。
例子:

Input : "Ravi had been saying that he had been there"
Output : had
 
Input : "Ravi had been saying that"
Output : No Repetition

Input : "he had had he"
Output : he

我们有针对这个问题的现有解决方案,请参阅 Find the first repeat word in a 字符串链接。我们可以在Python中使用 Dictionary 数据结构快速解决这个问题。做法很简单,

  1. 首先拆分给定的字符串,用空格分隔。
  2. 现在使用 collections.Counter(iterator) 方法将单词列表转换为字典。字典包含单词作为键,它的频率作为值。
  3. 现在再次遍历单词列表并检查哪个单词的频率大于 1。
# Function to Find the first repeated word in a string 
from collections import Counter 
  
def firstRepeat(input): 
      
    # first split given string separated by space 
    # into words 
    words = input.split(' ') 
      
    # now convert list of words into dictionary 
    dict = Counter(words) 
  
    # traverse list of words and check which first word 
    # has frequency > 1 
    for key in words: 
        if dict[key]>1: 
            print (key) 
            return
  
# Driver program 
if __name__ == "__main__": 
    input = 'Ravi had been saying that he had been there'
    firstRepeat(input) 

输出:

had