Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将字符串转换为字典,并计算每个单词的数量_Python_String_Dictionary_Python 3.x - Fatal编程技术网

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

Python 如何将字符串转换为字典,并计算每个单词的数量,python,string,dictionary,python-3.x,Python,String,Dictionary,Python 3.x,我只是想知道如何转换一个字符串,比如“hello there hi there”,并将其转换为字典,然后使用这本字典,我想计算字典中每个单词的数量,并按字母顺序返回。因此,在这种情况下,它将返回: [('hello', 1), ('hi', 1), ('there', 2)] 任何帮助都将不胜感激 >>> from collections import Counter >>> text = "hello there hi there" >>>

我只是想知道如何转换一个字符串,比如“hello there hi there”,并将其转换为字典,然后使用这本字典,我想计算字典中每个单词的数量,并按字母顺序返回。因此,在这种情况下,它将返回:

[('hello', 1), ('hi', 1), ('there', 2)]
任何帮助都将不胜感激

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

计数器
是用于计算散列对象的
dict
子类。它是一个无序集合,其中元素存储为字典键,其计数存储为字典值。计数允许为任何整数值,包括零或负计数。
计数器
类类似于其他语言中的bags或Multiset


jamylak在
计数器上做得很好。这是一种无需导入
计数器的解决方案

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[w]=dic.get(w,0)+1而不是
if-else
1。您可以使用
{}
而不是
dict()
2<代码>如果dic中有w:
在没有
dic.keys()的情况下仍能正常工作。
3
dic[w]+=1
而不是
dic[w]=dic[w]+1
。如果您不想使用计数器;您可以使用
dic=collections.defaultdict(int)
并删除
if/else
。这是
>>> dic
{'hi': 1, 'there': 2, 'hello': 1}