2016-01-25 65 views
0

每行包含一個特殊的時間戳,主叫號碼,接收者號碼,以秒爲單位的呼叫持續時間和以分鐘爲單位的每分鐘費率, 「;」。該文件包含幾千個看起來像這樣的電話。我創建了一個列表而不是字典來訪問元素,但我不確定如何計算來自有問題的電話的呼叫數python3:在列表中重複計數

timestamp;caller;receiver;duration;rate per minute 
    1419121426;7808907654;7807890123;184;0.34 
    1419122593;7803214567;78;46;0.37 
    1419122890;7808907654;7809876543;225;0.31 
    1419122967;78;7808907654;419;0.34 
    1419123462;7804922860;7809876543;782;0.29 
    1419123914;98;78;919;0.34 
    1419125766;7807890123;7808907654;176;0.41 
    1419127316;7809876543;98;471;0.31 

    Phone number || # |Duration | Due  | 
    +--------------+----------------------- 
    |(780) 123 4567||384|55h07m53s|$ 876.97| 
    |(780) 123 6789||132|17h53m19s|$ 288.81| 
    |(780) 321 4567||363|49h52m12s|$ 827.48| 
    |(780) 432 1098||112|16h05m09s|$ 259.66| 
    |(780) 492 2860||502|69h27m48s|$1160.52| 
    |(780) 789 0123||259|35h56m10s|$ 596.94| 
    |(780) 876 5432||129|17h22m32s|$ 288.56| 
    |(780) 890 7654||245|33h48m46s|$ 539.41| 
    |(780) 987 6543||374|52h50m11s|$ 883.72| 

list =[i.strip().split(";") for i in open("calls.txt", "r")] 
print(list) 
+0

你準確計算什麼? – haifzhan

+0

來自呼叫方電話的呼叫數量 –

回答

0

這應該讓你開始

import csv 
import collections 

Call = collections.namedtuple("Call", "duration rate time") 

calls = {} 
with open('path/to/file') as infile: 
    for time, nofrom, noto, dur, rate in csv.reader(infile): 
     calls.get(nofrom, {}).get(noto,[]).append(Call(dur, rate, time)) 

for nofrom, logs in calls.items(): 
    for noto, callist in logs.items(): 
     print(nofrom, "called", noto, len(callist), "times") 
1

我甲肝e非常簡單的解決方案爲您的問題:

首先使用with當打開文件 - 這是一個方便的快捷方式,它提供了相同的功能,將此功能包裝到try ...除外。考慮到這一點:

lines = [] 
with open("test.txt", "r") as f: 
    for line in f.readlines(): 
     lines.append(line.strip().split(";")) 
print(lines) 

counters = {} 
# you browse through lists and later through numbers inside lists 
for line in lines: 
    for number in line: 
     # very basic way to count occurences 
     if number not in counters: 
      counters[number] = 1 
     else: 
      counters[number] += 1 
# in this condition you can tell what number of digits you accept 
counters = {elem: counters[elem] for elem in counters.keys() if len(elem) > 5} 
print(counters) 
+0

HeY @PatNowak我需要添加呼叫數量,但現在我想知道應該如何累加會費? –