【问题标题】:Summing values in Counter dictionary对 Counter 字典中的值求和
【发布时间】:2018-04-23 10:18:56
【问题描述】:

我有一本字典,它可以显示电影剧本中“女人”说了多少个单词。现在我想把字典的值加起来,这样我就得到了“女人”所说的单词的总数。 有没有办法做到这一点?

'WOMAN': Counter({'Mia': 4,
                           'a': 4,
                           'the': 4,
                           'and': 3,
                           'is': 3,
                           'on': 3,
                           '--': 3,
                           'it': 2,
                           'Then': 2,
                           'STUDIO': 2,
                           'Cappuccino,': 1,                              
                           'from': 1,
                           'her.': 1,
                           'No,': 1,
                           'I': 1,
                           'insist.': 1,
                           'She': 1,
                           'pays.': 1,
                           'smiles': 1,
                           'at': 1,
                           'drops': 1,
                           'bill': 1,
                           'in': 1,
                           'tip': 1,
                           'jar.': 1,
                           'watches': 1,
                           'as': 1,
                           'Woman': 1,
                           'walks': 1,
                           'off,': 1,
                           'joined': 1,
                           'screen:': 1,
                           '4:07.': 1})})

【问题讨论】:

  • sum(Counter({...}).values())

标签: python python-3.x dictionary counter


【解决方案1】:

从文档here,您可以使用sum(Counter.values())

d = {'women':Counter()}    
sum(d['women'].values())

【讨论】:

    【解决方案2】:

    假设你必须事先拆分你的字符串来提取单词,你可以在更早的阶段计算单词的数量:

    from collections import Counter
    
    x = 'this is a test string with this string repeated'
    
    words_split = x.split()
    
    count, c = len(words_split), Counter(words_split)
    
    print(count)
    # 9
    
    print(c)
    # Counter({'this': 2, 'string': 2, 'is': 1, 'a': 1, 'test': 1, 'with': 1, 'repeated': 1})
    

    【讨论】:

      猜你喜欢
      • 2015-12-24
      • 2015-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-27
      • 2015-07-31
      • 1970-01-01
      相关资源
      最近更新 更多