[英]Transform every word in string to a dict and pass how many times all the word occured as value in python
我在轉換字典中字符串的每個單詞並傳遞該單詞作為值出現的次數時遇到問題。 例如
string = 'How many times times appeared in this many times'
我想要的字典是:
dict = {'times':3, 'many':2, 'how':1 ...}
使用計數器
from collections import Counter
res = dict(Counter(string.split()))
#{'How': 1, 'many': 2, 'times': 3, 'appeared': 1, 'in': 1, 'this': 1}
您可以遍歷單詞並增加計數,如下所示:
d = {}
for word in string.split(" "):
d.setdefault(word, 0)
d[word] += 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.