[英]Get only unique words from a sentence in 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:]]
首先 - 用空格分隔符(split() 方法)拆分字符串,然后使用 Counter 或通過您自己的代碼計算頻率。
您可以使用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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.