python處理文件(.csv)

運用:文件讀寫、字符串截取、字典dict、集合set

#!/usr/bin/python

# -*- coding: utf-8 -*-
'''
Created on 8, 2013
@author: xue
Filename : 1.py

'''
CITY = {
        '010':1000,
        '020':1000,
        '021':1000,
        '0755':1000
        }

BUS_INPUT_FILE     = "D:/work/svn/testassess/tools/search/platform/log/bus_all.csv"
BUS_OUPUT_PATH     = "D:/work/svn/testassess/tools/search/platform/log/output/bus_all/"

def getCityCodeByPoiId(strPoiId):
    strCityCode = strPoiId[3:6]
    strCityCode = str(int(strCityCode.upper(), 16))  #十六進制 to十進制
    if len(strCityCode)<4:
        strCityCode = "0"+ strCityCode;
    return strCityCode

def isInCity(citycode):
    bCity = False
    for i in CITY:
        if i == citycode:
            bCity = True
            break
    return bCity

def busData():
    #finput = open("D:/work/svn/testassess/tools/search/platform/log/bus_all.csv")   # 返回一個文件對象
    #foutput = open(BUS_OUTPUT_PATH + "result.txt", 'w')
    finput = open(BUS_INPUT_FILE)
    line = finput.readline()           # 調用文件的 readline()方法
    n = 0
    dict_city2name = dict()
    while line:
        s = line.split(',')
        n += 1
        if n > 1 and len(s) >= 4:
            busname = s[1]
            busname = busname[1:len(busname)]
            index = busname.rfind('(')
            if index != -1:
                busname = busname[0:index]
            poiid = s[3]
            citycode = getCityCodeByPoiId(poiid)
            if isInCity(citycode):
                count = CITY[citycode]
                iscity = False
                for key in dict_city2name:
                    if citycode == key:
                        iscity = True
                        break
                if iscity:
                    if len(dict_city2name[citycode]) < count:
                        dict_city2name[citycode].add(busname)
                else:
                    set_name = set()
                    set_name.add(busname)
                    dict_city2name[citycode] = set_name
        line = finput.readline()
    finput.close()
    for key in dict_city2name:
        foutput = open(BUS_OUPUT_PATH + key + ".txt", 'w')
        for name in dict_city2name.get(key):
            foutput.write(name + '\n')
    foutput.close()

    
if __name__ == '__main__':
       busData()    #公交站數據,CSV格式
  
發佈了20 篇原創文章 · 獲贊 12 · 訪問量 31萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章