简体   繁体   English

如何将字符串转换为字典,并计算每个单词的数量

[英]How to convert string to dictionary, and count the number of each word

I am just wondering how i would convert a string, such as "hello there hi there", and turn it into a dictionary, then using this dictionary, i want to count the number of each word in the dictionary, and return it in alphabetic order. 我只是想知道我将如何转换字符串,如“你好那里好”,然后把它变成字典,然后使用这个字典,我想计算字典中每个单词的数量,并以字母顺序返回订购。 So in this case it would return: 所以在这种情况下它会返回:

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

any help would be appreciated 任何帮助,将不胜感激

>>> 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])

A Counter is a dict subclass for counting hashable objects. Counter是用于计算可哈希对象的dict子类。 It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. 它是一个无序集合,其中元素存储为字典键,其计数存储为字典值。 Counts are allowed to be any integer value including zero or negative counts. 计数允许为任何整数值,包括零或负计数。 The Counter class is similar to bags or multisets in other languages. Counter类与其他语言的bag或multisets类似。

jamylak did fine with Counter . jamylak对Counter很好。 this is a solution without importing 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

gives

>>> dic
{'hi': 1, 'there': 2, 'hello': 1}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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