Chinaunix首页 | 论坛 | 博客
  • 博客访问: 473367
  • 博文数量: 65
  • 博客积分: 2645
  • 博客等级: 少校
  • 技术积分: 675
  • 用 户 组: 普通用户
  • 注册时间: 2006-01-08 17:04
文章分类

全部博文(65)

文章存档

2010年(5)

2009年(5)

2008年(14)

2007年(35)

2006年(6)

分类: Python/Ruby

2007-07-05 23:56:32

今天需要处理一些数据,试着用python写了一个脚本来处理 ^^
----------------------------------------------------------
需要把文件:
200000000000101,0,0,2000,0,0,500,1500,3800,1000
200000000000102,0,0,2000,0,0,500,1500,3800,1000
...
处理成:
200000000000101,0, 010101103,0
200000000000101,1, 010101210,0
200000000000101,2, 010101221,2000
200000000000101,3, 010101240,0
200000000000101,4, 010101250,0
200000000000101,5, 010101914,500
200000000000101,6, 010101340,1500
200000000000101,7, 010101341,3800
200000000000101,8, 010101905,1000
200000000000102,0, 010101103,0
200000000000102,1, 010101210,0
200000000000102,2, 010101221,2000
200000000000102,3, 010101240,0
...
(格式:套餐id, 序列号, 子业务标志, 收取的费用)
----------------------------------------------------------
#!/usr/bin/python
# Filename: format.py
# -*- coding: utf-8 -*-

# string5字段, 依次为 idd,  来电显示 010101210 , ...
subsvc = ['010101103', '010101210', '010101221', '010101240', '010101250', '010101914', '010101340', '010101341', '010101905']

myfile = open("prcpln.txt")
myfile.seek(0)
str = myfile.read()

for line in str.split('\n'):

    ss = line.split(',', 1)

    vv = ss[1].split(',')
    
    for i in range(len(vv)):       
        #套餐id, 序列号, 子业务标志, 收取的费用
        print ss[0] + ',' + repr(i) + ',' + subsvc[i] + ',' + vv[i]
       
   
myfile.close()
--------------------------------------------
在cmd中执行  format.py > out.txt ^^

附:
2008-06-21 第二版

#!/usr/bin/env python
#coding=GBK
#!/usr/bin/env python

def text2dict_list(filename, var_list, sep = ','):
    dict_list = []
    dict_tmp={}
    a = open(filename)
    for line in a:
        if line[0:1] == '#':
            continue
        dict_tmp = {}
        for name, value in zip(var_list, line.replace('\n', '').split(sep)):
            dict_tmp[name] = value
        dict_list.append(dict_tmp)
    a.close()
    
    return dict_list


def test():
    var_list=['prcplnid','010101103', '010101210', '010101221', '010101240', '010101250', '010101914', '010101340', '010101341', '010101905']
    dict_list = text2dict_list("
prcpln.txt", var_list)

    for record in dict_list:
        i = 0
        for key in var_list[1:]:
            print record['prcplnid'], i, key, record[key]
            i = i + 1

    print "Over"



if __name__ == "__main__":
    test()

阅读(2286) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~