[英]How to sum the values of same key from txt file using python
I am trying to sum up values of same key from txt file我正在尝试从 txt 文件中总结相同键的值
The txt file looks like txt文件看起来像
**record count**
|
** Type**
--|--
4
|
Employee
3
|
Employee
8
|
Post
6
|
Post
I want to sum the employee record count and post record count我想总结员工记录数和职位记录数
Expected output is预期输出是
Employee: 7
Post :14
My code is:我的代码是:
Dataa ={'Employee':0, 'Post':0}
With open('new.txt', 'r') as f_in:
for line in map(str.strip, f_in)
if not line:
continue
name, cnt =line.split()
if name not in Dataa:
Dataa[name] =int(cnt)
else:
Dataa[name]+=int(cnt)
for name in sorted(Dataa):
Print(name, Dataa[name])
But i am getting below error但我得到低于错误
name, cnt=line.split()
ValueError: too many values to unpack(excepted 2)
Please help me with solution.请帮我解决问题。
You can use regex
to parse your text file:您可以使用regex
来解析您的文本文件:
import re
with open('new.txt', 'r') as f:
data = f.read()
for name in ['Employee', 'Post']:
res = re.findall(f'(\d+)\n\|\n{name}', data)
print(f'{name}: {sum([int(e) for e in res])}')
Output:输出:
Employee: 7
Post: 14
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.