【问题标题】:Need suggestion on best structure to build a token dictionary in Python需要有关在 Python 中构建标记字典的最佳结构的建议
【发布时间】:2013-04-09 13:16:38
【问题描述】:

我对python很陌生,希望得到关于这个问题的建议。

我希望在 python 中创建一个令牌字典。首先,让我简要描述一下我需要什么样的功能。

  1. 假设每个现有记录应该是 {word, type, count}。例如。蛇,NN,10
  2. 每当出现新记录 {word, type} 时,它都会检查字典是否存在。如果找到,计数 += 1。否则,添加计数为 1 的新记录。
  3. 字典可以按最高计数排序

关于最佳结构的任何建议并给我展示示例?

提前致谢!

【问题讨论】:

  • 使用collections.Counter

标签: python data-structures python-2.7


【解决方案1】:

collections.Counter 为您服务。

【讨论】:

    【解决方案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)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      相关资源
      最近更新 更多