使用Python计算唯一单词并创建包含单词和数量的字典

2024-10-01 19:23:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要帮助创建一个名为strcount(S)的函数,该函数返回一个以单词为键的字典,以及单词作为相应值出现的次数。输出应该如下所示:

strcount("a a a a b b")
{'a': 4, 'b': 2}
strcount("one")
{'one': 1}
sorted(strcount("this one and that one for one time").items())
[('and', 1), ('for', 1), ('one', 3), ('that', 1), ('this', 1), ('time', 1)]

Tags: and函数for字典thattimeitemsthis
3条回答

最典型的解决方案是使用collections.Counter

>>> from collections import Counter
>>> Counter("this one and that one for one time".split()).items()
[('and', 1), ('for', 1), ('that', 1), ('this', 1), ('one', 3), ('time', 1)]

如果您想编写自己的解决方案,我会尝试如下方法:

  1. 将字符串拆分为单词列表。您可以使用.split()进行此操作。在
  2. 构造一个字典,其中每个键是一个单词,值是0。在
  3. 重复你的单词列表。对于每个单词,将1添加到your_dict[word]。在

@Blender使用^{}的回答很好,但它适用于Python 2.7及更高版本。在

下面是一个适用于较低版本Python的替代解决方案:

from collections import defaultdict

word_freq = defaultdict(int)
for i in "this one and that one for this one".split():
   word_freq[i] += 1

这将为您提供:

^{pr2}$

或者,您可以不使用Counter来实现自己的算法。

def countwords(A):  
    dic = {}  
    for item in A.split():  
       if dic.has_key(item):  
           dic[item] += 1  
       else:  
           dic[item] = 1  

    return sorted(dic.items())  # return sorted list.

如果使用的是Python 3.x,请替换以下行:

^{pr2}$

有:

if item in dic:

输出:

>>> print (countwords("this one and that one for one time"))
[('and', 1), ('for', 1), ('one', 3), ('that', 1), ('this', 1), ('time', 1)]

相关问题 更多 >

    热门问题