[英]How to sum the values of same key from txt file using python
我正在嘗試從 txt 文件中總結相同鍵的值
txt文件看起來像
**record count**
|
** Type**
--|--
4
|
Employee
3
|
Employee
8
|
Post
6
|
Post
我想總結員工記錄數和職位記錄數
預期輸出是
Employee: 7
Post :14
我的代碼是:
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])
但我得到低於錯誤
name, cnt=line.split()
ValueError: too many values to unpack(excepted 2)
請幫我解決問題。
您可以使用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])}')
輸出:
Employee: 7
Post: 14
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.