python处理文件(.csv)

本文介绍了一种处理公交站点数据的方法,通过读取CSV格式的数据文件,提取并筛选出特定城市的公交线路名称,最终将结果按城市分别输出到不同的文件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

运用:文件读写、字符串截取、字典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格式
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值