簡體   English   中英

如何使用python對txt文件中相同鍵的值求和

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM