在Python中找到字符串中第一个重复的单词?
给定一个字符串。我们的任务是在给定的字符串中找到第一个重复的单词。要实现此问题,我们使用Python集合。从集合中,我们可以获得Counter()方法。
算法
Repeatedword(n) /* n is the string */ Step 1: first split given string separated by space into words. Step 2: now convert the list of words into a dictionary. Step 3: traverse list of words and check which the first word has frequency >1
范例程式码
# To Find the first repeated word in a string from collections
import Counter
def repeatedword(n):
# first split given string separated by space into words
w = n.split(' ')
con = Counter(w)
for key in w:
if con[key]>1:
print ("REPEATED WORD IS ::>",key)
return
# Driver program
if __name__ == "__main__":
n=input("Enter the String ::")
repeatedword(n)输出结果
Enter the String ::We are all peaceful soul and blissful soul and loveful soul happy soul REPEATED WORD IS ::> soul
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿