2013-04-09 18 views
0

我对Python很新,希望得到关于这个问题的建议。需要关于在Python中构建一个令牌字典的最佳结构建议

我希望在python中创建一个令牌字典。首先,让我简要介绍一下我需要的功能。

  1. 假设每个现有的记录应该是{word,type,count}。例如。蛇,NN,10
  2. 无论何时出现新记录{word,type},它都会检查字典是否存在。如果找到了,算上+ = 1。否则,用数增加新的记录1.
  3. 字典能够排序最高计数

上最好的结构有任何建议,让我看看例子就可以了?

在此先感谢!

+0

使用'collections.Counter'。 – 2013-04-09 13:18:29

回答

2

您可以使用collections.Counter()(在py2.7介绍):

In [52]: from collections import Counter 

In [53]: c=Counter("aaabbc") 

In [54]: c 
Out[54]: Counter({'a': 3, 'b': 2, 'c': 1}) 

In [55]: c.most_common() 
Out[55]: [('a', 3), ('b', 2), ('c', 1)] 

和py2.6你可以使用collections.defaultdict

In [58]: from collections import defaultdict 

In [59]: strs="aaabbc" 

In [61]: dic=defaultdict(int) 

In [62]: for x in strs: 
    ....:  dic[x]+=1 
    ....:  

In [63]: dic 
Out[63]: defaultdict(<type 'int'>, {'a': 3, 'c': 1, 'b': 2}) 

In [64]: from operator import itemgetter 

In [66]: sorted(dic.items(),reverse=True,key=itemgetter(1)) 
Out[66]: [('a', 3), ('b', 2), ('c', 1)]