仅从 Python 中的句子中获取唯一的单词



假设我有一个字符串,上面写着"芒果芒果桃子"。如何仅打印该字符串中的唯一单词。 上述字符串的所需输出将是 [peach] 作为列表 谢谢!!

Python 有一个名为 count 的内置方法,在这里可以很好地工作

text = "mango mango peach apple apple banana"
words = text.split()
for word in words:
if text.count(word) == 1:
print(word)
else:
pass
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 mango.py 
peach
banana

使用列表理解,你可以做到这一点

[print(word) for word in words if text.count(word) == 1]
seq = "mango mango peach".split()
[x for x in seq if x not in seq[seq.index(x)+1:]]

这是使用集合的另一种解决方案。

sentence = "mango mango peach"
# Convert the sentence into a list
words = sentence.split()
print(words)
# Convert the list into a set. Only unique words will be stored in the set
unique_words = set(words)
print(unique_words)

首先 - 用空格分隔符(split((方法(拆分字符串,然后使用计数器或通过自己的代码计算频率。

您可以使用Counter来查找每个单词的出现次数,然后列出仅出现一次的所有单词。

from collections import Counter
phrase = "mango peach mango"
counts = Counter(phrase.split())
print([word for word, count in counts.items() if count == 1])
# ['peach']

最新更新