0

我想在字典中添加数字,累积,所以它会添加字典的键。

x = ' '
dict = {}
list = []
while x != '':
x = raw_input('Enter line:')
p = x.split(' ')
if x != '':
    list.append(p)
result = sum(list, [])
result = result
num = []
for a in result:
for n in dict:
    p = a.count(a)
    l = a
    if n == l:
        l += l
dict[a] = p
print dict

raw_input('')

我希望“dict”由输入中的单词和输入的次数组成。谢谢

4

3 回答 3

3

Python 2.7 有collections.Counter它可以用来给你一个运行的单词总数。

于 2012-08-12T04:39:26.710 回答
3

使用Counter

from collections import Counter
x=raw_input('enter line\n')
if x.strip():
    x=x.split()
    count=Counter(x)
    dic=dict(count)
    print dic
else:
    print 'you entered nothing'

输出:

>>> 
enter line
cat cat spam eggs foo foo bar bar bar foo
{'eggs': 1, 'foo': 3, 'bar': 3, 'cat': 2, 'spam': 1}

并且不使用Counter(不推荐)你可以使用sets

dic= {}
x = raw_input('Enter line:')
if x.strip():
    p = x.split()
    for x in set(p):   #set(p) contains only unique elements of p
        dic[x]=p.count(x)
    print dic
else:
    print 'you entered nothing'

输出:

>>> 
Enter line: cat cat spam eggs foo foo bar bar bar foo
{'eggs': 1, 'foo': 3, 'bar': 3, 'cat': 2, 'spam': 1}
于 2012-08-12T04:45:25.727 回答
2
from collections import Counter

lines = iter(lambda: raw_input('Enter line:'), '') # read until empty line
print Counter(word for line in lines for word in line.split()).most_common()
于 2012-08-12T04:52:36.470 回答