繁体   English   中英

如何对相同的字符串求和并从 python 中的 txt 文件中对它们进行排序

[英]How to sum identical strings and sort them from txt file in python

我有一个 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 地址和总字节组合在一起,按字节排序。 就像excels的“在多个工作表中合并数据”一样

我需要得到这个:

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

我真的不明白该怎么做。
在此先感谢您的时间!

使用字典

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}')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM