2014-09-22 4 views
-2

Привет, ребята У меня вопрос, как суммировать одинаковые IP-адреса в словаре. У меня есть входной файл, этот файл выглядит следующим образом:Python dictionary sum

IP   , Byte 
10.180.176.61,3669 
10.164.134.193,882 
10.164.132.209,4168 
10.120.81.141,4297 
10.180.176.61,100 

Моего шаг, чтобы открыть этот файл и разобрать IP-адрес с номером после запятой, так что я могу суммировать все байты для одного IP-адреса. Таким образом, я могу получить результат, как:

IP 10.180.176.61 , 37669 

Мой код выглядит следующим образом:

#!/usr/bin/python 
# -*- coding: utf-8 -*- 

import re,sys, os 
from collections import defaultdict 

f  = open('splited/small_file_1000000.csv','r') 
o  = open('gotovo1.csv','w') 

list_of_dictionaries = {} 

for line in f: 
    if re.search(r'\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}.*',line): 
     line_ip = re.findall(r'\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}',line)[0] 
     line_by = re.findall(r'\,\d+',line)[0] 
     line_b = re.sub(r'\,','',line_by) 

     list_of_dictionaries['IP'] = line_ip 
     list_of_dictionaries['VAL'] = int(line_b) 


c = defaultdict(int) 
for d in list_of_dictionaries: 
    c[d['IP']] += d['VAL'] 

print c 

Любая идея будет здорово.

ответ

1

Используйте csv модуль для чтения файла и collections.Counter подводить итоги за IP-адрес:

from collections import Counter 
import csv 


def read_csv(fn): 
    with open(fn, 'r') as csvfile: 
     reader = csv.reader(csvfile, delimiter=',') 
     reader.next() # Skip header 
     for row in reader: 
      ip, bytes = row 
      yield ip, int(bytes) 


totals = Counter() 
for ip, bytes in read_csv('data.txt'): 
    totals[ip] += bytes 

print totals 

Выход:

Counter({'10.120.81.141': 4297, '10.164.132.209': 4168, '10.180.176.61': 3769, '10.164.134.193': 882}) 
0

Если ваш файл выглядит как пример вы предоставили вам не Для его анализа нужны регулярные выражения. Просто разбить строку с помощью запятой:

list_of_dictionaries = {} 
with open('splited/small_file_1000000.csv', 'r') as f: 
    header = f.readline() 
    for line in f: 
      ip, bytes = line.split(',') 
      if list_of_dictionaries.has_key(ip): 
       list_of_dictionaries[ip] += int(bytes.strip()) 
      else: 
       list_of_dictionaries[ip] = int(bytes.strip()) 
OUT: {'10.180.176.61': 3769, '10.164.134.193': 882, '10.164.132.209': 4168, '10.120.81.141': 4297}