每一行包含一个特殊的时间戳,来电号码,接收者号码,呼叫持续时间(以秒为单位)和每分钟收费的分数(以分钟为单位),全部用&#34 ;;分隔。该文件包含数千个看起来像这样的调用。我创建了一个列表而不是字典来访问元素,但我不确定如何计算来自相关电话的来电数量
$anyVariable
答案 0 :(得分:1)
我的解决方案非常简单:
首先在打开文件时使用with
- 它是一个方便的快捷方式,它提供相同的功能,将此功能包装到try ... except。考虑一下:
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)
答案 1 :(得分: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")