Python 如何将字符串转换为字典,并计算每个单词的数量
我只是想知道如何转换一个字符串,比如“hello there hi there”,并将其转换为字典,然后使用这本字典,我想计算字典中每个单词的数量,并按字母顺序返回。因此,在这种情况下,它将返回: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', 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()的情况下仍能正常工作。
3dic[w]+=1
而不是dic[w]=dic[w]+1
。如果您不想使用计数器;您可以使用dic=collections.defaultdict(int)
并删除if/else
。这是
>>> dic
{'hi': 1, 'there': 2, 'hello': 1}