繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM