【问题标题】:Merge counter.items() dictionaries into one dictionary将 counter.items() 字典合并到一个字典中
【发布时间】:2017-01-04 17:35:55
【问题描述】:

如何将此代码的输出放入包含键值对总数的字典中?

import re
from collections import Counter

splitfirst = open('output.txt', 'r')
input = splitfirst.read()
output = re.split('\n', input)

for line in output:
    counter = Counter(line)
    ab = counter.items() #gives list of tuples will be converted to dict
    abdict = dict(ab)
    print abdict

这是我得到的示例:

{' ': 393, '-': 5, ',': 1, '.': 1}
{' ': 382, '-': 4, ',': 5, '/': 1, '.': 5, '|': 1, '_': 1, '~': 1}
{' ': 394, '-': 1, ',': 2, '.': 3}
{'!': 1, ' ': 386, 'c': 1, '-': 1, ',': 3, '.': 3, 'v': 1, '=': 1, '\\': 1, '_': 1, '~': 1}
{'!': 3, ' ': 379, 'c': 1, 'e': 1, 'g': 1, ')': 1, 'j': 1, '-': 3, ',': 2, '.': 1, 't': 1, 'z': 2, ']': 1, '\\': 1, '_': 2}

我有 400 个这样的字典,理想情况下我必须将它们合并在一起,但如果我理解正确,Counter 不会全部提供,而是一个接一个地提供。

任何帮助将不胜感激。

【问题讨论】:

    标签: python python-2.7 dictionary merge counter


    【解决方案1】:

    + 运算符合并计数器:

    >>> Counter('hello') + Counter('world')
    Counter({'l': 3, 'o': 2, 'e': 1, 'r': 1, 'h': 1, 'd': 1, 'w': 1})
    

    所以你可以使用sum 来组合它们的集合:

    from collections import Counter
    
    with open('output.txt', 'r') as f:
        lines = list(f)
    
    counters = [Counter(line) for line in lines]
    combined = sum(counters, Counter())
    

    (您也不需要使用正则表达式将文件拆分为行;它们已经是行的迭代。)

    【讨论】:

    • 我得到错误:combined = sum(counters) TypeError: unsupported operand type(s) for +: 'int' and 'Counter'
    • @KristianVybiral:我忘记了初始值,抱歉!应该是sum(counters, Counter())。
    • 非常感谢!太棒了!我不确定这到底是如何工作的,因为我的想法完全不同。
    【解决方案2】:

    这是您的问题的mcve:

    import re
    from collections import Counter
    
    data = """this is the first line
    this is the second one
    this is the last one
    """
    
    output = Counter()
    for line in re.split('\n', data):
        output += Counter(line)
    
    print output
    

    在您的示例中应用该方法,您会得到:

    import re
    from collections import Counter
    
    with open('output.txt', 'r') as f:
        data = f.read()
    
        output = Counter()
        for line in re.split('\n', data):
            output += Counter(line)
    
        print output
    

    【讨论】:

    • 谢谢,这很有帮助
    猜你喜欢
    • 1970-01-01
    • 2019-05-16
    • 2020-11-13
    • 2017-04-11
    • 1970-01-01
    • 2017-11-27
    • 2021-03-13
    • 2017-07-23
    • 1970-01-01
    相关资源
    最近更新 更多