Python:返回字符串中仅出现一次的单词

标签 python string set find-occurrences

假设我有一个函数,它接受某个字符串,然后我需要返回该字符串中仅出现一次的单词集。这样做的最佳方法是什么?使用 dict 有帮助吗?我尝试过一些伪代码,例如:

counter = {}
def FindWords(string):
    for word in string.split()
        if (word is unique): counter.append(word)
return counter

有没有更好的方法来实现这个?谢谢!

编辑:

假设我有:“这个男孩跳过了另一个男孩”。我想返回“跳跃”、“越过”和“其他”。

此外,我想将其作为一组返回,而不是列表。

最佳答案

您可以使用集合中的计数器并返回一组仅出现一次的单词。

from collections import Counter

sent = 'this is my sentence string this is also my test string'

def find_single_words(s):
    c = Counter(s.split(' '))
    return set(k for k,v in c.items() if v==1)

find_single_words(sent)
# returns:
{'also', 'sentence', 'test'}
<小时/>

要仅使用基本 Python 实用程序来执行此操作,您可以使用字典来记录出现次数,从而复制 Counter 的功能。

sent = 'this is my sentence string this is also my test string'

def find_single_words(s):
    c = {}
    for word in s.split(' '):
        if not word in c:
             c[word] = 1
        else:
             c[word] = c[word] + 1
    return [k for k,v in c.items() if v==1]

find_single_words(sent)
# returns:
['sentence', 'also', 'test']

关于Python:返回字符串中仅出现一次的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46554248/

相关文章:

组合独立集/汉明距离的算法/近似

python - 在 Django 模板中为 Highcharts 设置 Pandas 数据帧中的 JSON 格式

python - 如何按以太网MAC地址过滤

string - 如何检测字符串中的回文循环长度?

c# - 从字符串的开头和字符串的结尾删除单引号

c# - C# 如何删除字符串中的最后一个字符?

c# - 合并两个自定义类返回重复项

python - 从文本中删除一行

python - Matplotlib,全局设置刻度数。 X 轴、Y 轴、颜色条

java - 无法通过引用方法传递元素来将元素添加到集合中