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 配置索引值超出解析的列數(shù),請檢查配置!"
                        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 "請輸入正確啟動參數(shù),參考 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)
    


?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • # Python 資源大全中文版 我想很多程序員應該記得 GitHub 上有一個 Awesome - XXX 系列...
    aimaile閱讀 26,844評論 6 427
  • # Python 資源大全中文版 我想很多程序員應該記得 GitHub 上有一個 Awesome - XXX 系列...
    小邁克閱讀 3,129評論 1 3
  • 本文來自 我的博客。博客的文章保持更新,此文可能不是最新狀態(tài)。 下載、解壓 python 源代碼 從 python...
    jeromesun閱讀 70,014評論 0 5
  • Python 面向對象Python從設計之初就已經是一門面向對象的語言,正因為如此,在Python中創(chuàng)建一個類和對...
    順毛閱讀 4,375評論 4 16
  • 最近在看電視劇《紅高粱》,兩點感觸:1、上半年看《羋月傳》時,覺得黃軒演技不錯的呀,黃歇和羋月決裂那場戲爆發(fā)力很足...
    染柳煙濃閱讀 368評論 0 1

友情鏈接更多精彩內容