从字符串/文本文件创建字典

时间:2013-11-24 01:57:15

标签: python python-3.x

我想组装一个允许我从给定字符串甚至文本文件创建字典的函数。

例如:

statement = "tell me what you want what you really really want"

我希望最终结果如下:

{tell: 1, me:1, what: 2, you: 2, want: 2, really: 2}

字符串中的字符是键,而它出现的次数是值。

2 个答案:

答案 0 :(得分:2)

使用collections.Counter(),传递一系列单词来计算:

>>> from collections import Counter
>>> Counter('tell me what you want what you really really want'.split())
Counter({'you': 2, 'really': 2, 'what': 2, 'want': 2, 'tell': 1, 'me': 1})

答案 1 :(得分:1)

不导入任何内容:

statement = "tell me what you want what you really really want"

end_result = dict()

for word in statement.split():
    end_result[word] = end_result.get(word, 0) + 1