Python|从给定的句子中删除所有重复的单词
给定一个包含 n 个单词/字符串的句子。删除所有彼此相似的重复单词/字符串。
例子:
Input : Geeks for Geeks
Output : Geeks for
Input : Python is great and Java is also great
Output : is also Java Python and great
我们可以使用Python Counter() 方法快速解决这个问题。方法很简单。
1) 将用空格分隔的输入句子拆分为单词。
2)因此,首先要将所有这些字符串放在一起,我们将在给定的字符串列表中加入每个字符串。
3) 现在使用 Counter 方法创建一个字典,将字符串作为键,将它们的频率作为值。
4)加入每个单词都是唯一的,形成单个字符串。
Python
from collections import Counter
def remov_duplicates(input):
# split input string separated by space
input = input.split(" ")
# now create dictionary using counter method
# which will have strings as key and their
# frequencies as value
UniqW = Counter(input)
# joins two adjacent elements in iterable way
s = " ".join(UniqW.keys())
print (s)
# Driver program
if __name__ == "__main__":
input = 'Python is great and Java is also great'
remov_duplicates(input)
Python
# Program without using any external library
s = "Python is great and Java is also great"
l = s.split()
k = []
for i in l:
# If condition is used to store unique string
# in another list 'k'
if (s.count(i)>=1 and (i not in k)):
k.append(i)
print(' '.join(k))
Python3
# Python3 program
string = 'Python is great and Java is also great'
print(' '.join(dict.fromkeys(string.split())))
输出
and great Java Python is also
替代方法:-
Python
# Program without using any external library
s = "Python is great and Java is also great"
l = s.split()
k = []
for i in l:
# If condition is used to store unique string
# in another list 'k'
if (s.count(i)>=1 and (i not in k)):
k.append(i)
print(' '.join(k))
输出
Python is great and Java also
方法3:另一个更短的实现:
Python3
# Python3 program
string = 'Python is great and Java is also great'
print(' '.join(dict.fromkeys(string.split())))
输出
Python is great and Java also
https://youtu.be/tTjBhgJ
-NDE