Python 将counter.items()字典合并到一个字典中
如何将这段代码的输出输入到一个包含键:值对总数的字典中Python 将counter.items()字典合并到一个字典中,python,python-2.7,dictionary,merge,counter,Python,Python 2.7,Dictionary,Merge,Counter,如何将这段代码的输出输入到一个包含键:值对总数的字典中 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
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并没有给出全部,而是一个接一个地给出全部
任何帮助都将不胜感激 操作员合并计数器:
>>> 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())
(您也不需要使用正则表达式将文件拆分为多行;它们已经是多行了。)以下是您的问题:
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
我得到错误:combined=sum(counters)TypeError:不支持的+:'int'和'Counter'的操作数类型@KristianVybiral:对不起,我忘记了初始值!这将是
sum(counters,Counter())
。非常感谢!这太完美了!我不知道这到底是怎么回事,因为我的想法完全不同。谢谢,这非常有用