1. 程式人生 > >檔案裡內容的去重和統計

檔案裡內容的去重和統計

一個檔案如下:

 

找出相同元素的值的和並寫入檔案:

程式碼如下:

dict1 = {}
with open("統計檔案.txt",'r') as f:

# 按行讀取檔案
alist = f.readlines()

# 去除空行
for str in alist:
if str == '\n':
continue
else:
# 去除後邊的空格,並分割成列表
a = str.rstrip("\n")
blist = a.split(" ")

if blist[0] in dict1:
dict1[blist[0]] += int(blist[1])
else:
dict1[blist[0]] = int(blist[1])
print(dict1)
# 將結果格式化寫入檔案
with open("統計結果.txt","a") as file:
for key in dict1.keys():
file.write('{} {}\n'.format(key,dict1[key]))