我有一个txt文件(命名为file.txt(,它包含两列(ip地址和字节,[,,]-分隔符(
file = open(file='file.txt')
print(file.read())
output:
13.107.4.52,,323
184.51.238.190,,505
184.51.238.190,,505
96.17.7.76,,1066
185.48.81.253,,1061
40.127.240.158,,1443
13.107.42.16,,1544
20.190.160.15,,6342
20.86.249.62,,2700
52.109.12.19,,1435
52.109.12.19,,1435
184.51.238.190,,425
40.127.240.158,,1978
20.73.130.64,,2674
204.79.197.200,,943
204.79.197.200,,943
204.79.197.200,,776
我需要组合具有重复ip地址的行和按字节排序的总和字节。和excesses的";在多个工作表中合并数据";
我需要这个:
20.190.160.15,,6342
40.127.240.158,,3421
52.109.12.19,,2870
20.86.249.62,,2700
20.73.130.64,,2674
204.79.197.200,,2662
13.107.42.16,,1544
184.51.238.190,,1435
96.17.7.76,,1066
185.48.81.253,,1061
13.107.4.52,,323
我真的不明白该怎么做
提前感谢您抽出时间!
使用dict
from collections import defaultdict
d = defaultdict(int)
with open(file='file.txt') as f:
for line in f:
k,v = line.split(',,')
d[k] += int(v)
for k,v in sorted(d.items(), key=lambda x:x[-1], reverse=True):
print(f'{k},,{v}')