美文网首页
python 自带框架 csv 使用

python 自带框架 csv 使用

作者: 呵呵哒1991 | 来源:发表于2018-04-08 23:06 被阅读76次

官方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 自带框架 csv 使用

      本文链接:https://www.haomeiwen.com/subject/zxlvhftx.html