1. 在处理数据的时候碰到这样的问题,我有如下类似的数据
(1,0) 12
(1,1) 13
(1, 2) 15
(1,0) 8
(1,20) 89
(1, 23) 71
...
(2,1) 54
(2,3) 90
..
(15,1) 35
数据比较多,对数据的解释是,以第一条数据为例:(1,0) 12
(1,0)代表的是1号基站,0点时分,12代表的是记录的通话的cellphone数。(1,0) 12之间以空格分开。
现在大概知道基站的总数,从1开始编号,不同时间是从0-23点;这些数据保存在不同的部分文件夹下,现在需求是统计出每个基站在不同时间点出cellphone使用的总数。
现在我用python来处理。因为对Python不熟,下面是我的解决方案;
Step1: 遍历目录,找到保存这些数据的文件;
Step2 : 对于每一个文件,一行行读,然后通过split分割数据,先是分两部分,然后转化为Int型;
Step3: 通过数组来记录对应的值;
Step 4: 写到文本中
这里面涉及的几个问题:
1. 怎么将括号去掉;
2. 数值类型转换
3. 文件操作
下面是具体的代码:
#coding: utf-8
import os
from string import join
cell_count = [ [ 0 for col in range(24)] for row in range(20) ];
# cll_count is used to record the num of celphone
for root,dir,files in os.walk("./"): #pay attention to the os.walk();
for file in files:
if file.startswith("part"):
file_path = '/'.join([root,file]) #this is used to get the path of the file
print file_path
file_ = open(file_path)
for line in file_:
line_ = line.split()
cell = line_[0][1:len(line_[0])-1]
#print cell
#break
cell = cell.split(',')
cell_id = (int)(cell[0])
time = (int)(cell[1])
num = (int)(line_[1])
cell_count[cell_id][time] += num # ok tha's all
file_output_path = './result31.txt'
file_out = open(file_output_path,'w')
for data in cell_count:
data = str(data) # this is used to convert the int to string, only in this way can the data write into to the file
file_out.write(data+'\n')
print data
file_out.close();