Python的实际应用-数据处理(一) 遴选数据;

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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值