4

我只是想知道如何转换一个字符串,例如“hello there hi there”,然后把它变成一个字典,然后使用这个字典,我想计算字典中每个单词的数量,并以字母顺序返回命令。所以在这种情况下它会返回:

[('hello', 1), ('hi', 1), ('there', 2)]

任何帮助,将不胜感激

4

2 回答 2

14
>>> from collections import Counter
>>> text = "hello there hi there"
>>> sorted(Counter(text.split()).items())
[('hello', 1), ('hi', 1), ('there', 2)]

class collections.Counter([iterable-or-mapping])

ACounterdict用于计算可散列对象的子类。它是一个无序集合,其中元素存储为字典键,它们的计数存储为字典值。计数可以是任何整数值,包括零计数或负计数。该类Counter类似于其他语言中的bags 或multisets。

于 2013-05-15T06:01:52.490 回答
4

jamylak 做得很好Counter。这是一个不导入的解决方案Counter

text = "hello there hi there"
dic = dict()
for w in text.split():
    if w in dic.keys():
        dic[w] = dic[w]+1
    else:
        dic[w] = 1

>>> dic
{'hi': 1, 'there': 2, 'hello': 1}
于 2013-05-15T06:25:42.187 回答