python 自带框架 csv 使用

官方wiki
https://docs.python.org/2/library/csv.html
写的把 csv表转化成特定格式的小工具

#! /usr/bin/env  python
#coding=utf8
import os
import sys
import json 
import codecs  //   打开不同编码的文件
import csv  // 解析 csv  
def dd_data(confpath=None,inputfilepath=None,outfilepath=None):
    
    if not confpath or not inputfilepath or  not outfilepath:
        print "请保证路径正确!"
        syt.exit()
    conf_dic=json.load(open(confpath,"r"))
    out_f = open(outfilepath,"w+")
    map_dic = conf_dic.get("map_dic",{"zyid":0,"patientid":0})
    encoding = conf_dic.get("encoding","utf-8")
    split_str = conf_dic.get("split",",")
    if isinstance(split_str,unicode):
        split_str = split_str.encode("utf8")
    def utf_8_encoder(unicode_csv_data):
            for line in unicode_csv_data:
                yield line.encode('utf-8')
    with codecs.open(inputfilepath,"rb",encoding) as f:
        reader = csv.reader(utf_8_encoder(f)) 
        for row  in reader :
            #line= line.encode("utf-8")
            #line = line.strip().replace("\n","@@@@")
            #list = line.split(split_str)
            list = row if row else []
            if list :
                zy_id =list[map_dic.get("zyid",0)]
                patient_id = list[map_dic.get("patientid",0)]
                title= list[map_dic.get("title",0)] if "title" in map_dic else ""
                timestamp = list[map_dic.get("timestamp",len(list)-1)] if "timestamp" in map_dic else ""
                content = "<html>"
                for key,index in map_dic.items():
                    if key  in ["zyid","patientid","timestatmp","title"]:
                        continue
                    try:
                        single_content = list[index].strip().replace("\n","@@@@")   
                    except:
                        print "conf 配置索引值超出解析的列数,请检查配置!"
                        break
                        #sys.exit()
                    single_content = single_content.strip().replace("\n","@@@@")
                    #print type(single_content)
                    single_content = u"<p><p>%s:%s</p></p>"%(key,single_content.decode("utf8"))
                    content = content +single_content
                content = content +"</html>"
                out_f.write((u"%s\t%s\t%s\t%s\t%s\n"%(zy_id,patient_id,title,content,timestamp)).encode("utf8"))
    f.close()
    out_f.close()
    print "success out_path_file=%s"%(outfilepath)
        
    
if __name__ == "__main__":
    import argparse
    parser =argparse.ArgumentParser(description="--conf= --infilee= --outfile=")
    parser.add_argument("--conf",type=str,default=None)
    parser.add_argument("--infile",type=str,default=None)
    parser.add_argument("--outfile",type=str,default=None)
    #parser.add_argument("--help",type=str,defalut=None)    
    args = parser.parse_args()
    if not args.conf or not args.outfile  or not args.infile:
        print "请输入正确启动参数,参考 python mapper.py --conf=  --infile=  --outfile="
        example_conf = {"encoding":"utf8","map_dic":{"zyid(必须字段)":0,"patientid(必须字段)":1,"title":2,"主诉(内容字段中文名)":3,"timestamp(时间戳)":4}}
        print "\nconf实例\n%s"%(json.dumps(example_conf,ensure_ascii=False,indent=4))
        sys.exit()
    dd_data(args.conf,args.infile,args.outfile)
    


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • # Python 资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列...
    aimaile阅读 26,563评论 6 427
  • # Python 资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列...
    小迈克阅读 3,039评论 1 3
  • 本文来自 我的博客。博客的文章保持更新,此文可能不是最新状态。 下载、解压 python 源代码 从 python...
    jeromesun阅读 69,869评论 0 5
  • Python 面向对象Python从设计之初就已经是一门面向对象的语言,正因为如此,在Python中创建一个类和对...
    顺毛阅读 4,236评论 4 16
  • 最近在看电视剧《红高粱》,两点感触:1、上半年看《芈月传》时,觉得黄轩演技不错的呀,黄歇和芈月决裂那场戏爆发力很足...
    染柳烟浓阅读 342评论 0 1