2014-09-22 5 views
-2

안녕하세요 여러분, 어떻게 사전에 같은 IP 주소를 합산하는 질문이 있습니다.파이썬 사전 합계

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 주소를 구문 분석하는 것입니다 같은 나는 입력 파일을 해당 파일이 보인다.

#!/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 

어떤 생각이 좋은 것 :

IP 10.180.176.61 , 37669 

내 코드는 다음과 같습니다 그래서 나는 같은 결과를 얻을 수 있습니다.

답변

1

는 IP 주소 당 합계를 정리해 파일과 collections.Counter을 읽을 csv 모듈을 사용

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} 
: 그냥 쉼표를 사용하여 라인을 분할