首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python:返回字符串中准确发生一次的单词

Python:返回字符串中准确发生一次的单词
EN

Stack Overflow用户
提问于 2017-10-03 22:16:57
回答 5查看 4.1K关注 0票数 1

假设我有一个函数,它接受一些字符串,然后我需要返回这个字符串中的一组单词,这些单词恰好发生一次。做这件事最好的方法是什么?用dict会有帮助吗?我试过一些伪码,比如:

代码语言:javascript
复制
counter = {}
def FindWords(string):
    for word in string.split()
        if (word is unique): counter.append(word)
return counter

是否有更好的方法来实现这一点?谢谢!

编辑:

我说:“那个男孩跳过了另一个男孩”。我想返回“跳”、“跳”和“其他”。

另外,我想把它作为一个集合返回,而不是一个列表。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2017-10-03 22:22:43

您可以使用来自Countercollections,并返回一组只发生一次的单词。

代码语言:javascript
复制
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的功能。

代码语言:javascript
复制
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']
票数 3
EN

Stack Overflow用户

发布于 2017-10-03 22:29:03

这可能就是你想要的。

代码语言:javascript
复制
>>> counts = {}
>>> sentence =  "The boy jumped over the other boy"
>>> for word in sentence.lower().split():
...     if word in counts:
...         counts[word]+=1
...     else:
...         counts[word]=1
...         
>>> [word for word in counts if counts[word]==1]
['other', 'jumped', 'over']
>>> set([word for word in counts if counts[word]==1])
{'other', 'jumped', 'over'}

但是,正如其他人所建议的那样,使用藏书中的defaultdict更好。

票数 0
EN

Stack Overflow用户

发布于 2017-10-03 22:35:44

代码语言:javascript
复制
s='The boy jumped over the other boy'
def func(s):
    l=[]
    s=s.split(' ')  #edit for case-sensitivity here
    for i in range(len(s)):
        if s[i] not in s[i+1:] and s[i] not in s[i-1::-1]:
            l.append(s[i])
    return set(l)  #convert to set and return
print(func(s))

这应该挺好的。

检查每个元素是否与其前面或后面的列表中的元素匹配,如果没有,则追加它。

如果不想区分大小写,那么可以在拆分s=s.lower()s=s.upper()之前添加它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46554248

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档