python文件.csv和.dta格式互转

# csv 转 dta
dta_path = 'D:\标注\px支撑\脚本分项目\\test\dta\\'
csv_path = 'D:\标注\px支撑\脚本分项目\\test\csv\\'
for file in os.listdir(csv_path):
    data_frame = pd.read_csv(csv_path + file,encoding='utf-8')
    id = data_frame["ID"].tolist()
    patent = data_frame["patent"].tolist()
    abstract = data_frame["abstract"].tolist()
    biaozhu = data_frame["biaozhu"].tolist()
    for i in range(len(abstract)):
        line = abstract[i]
        if type(line) != float:
            # 设置编码格式
            line = line.encode("utf-8").decode("latin1")
            abstract[i] = line
    biaozhu = data_frame["biaozhu"].tolist()
    df = pd.DataFrame({'patent': patent,
                       'id': id,
                       'biaozhu': biaozhu,
                       'abstract': abstract })
    df.to_stata(dta_path+'\\'+'test.dta',version=117)


# dta 转 csv
dta_path = 'D:\\biaozhu\patent_claim_onlyabstract\dta\\'
csv_path = 'D:\\biaozhu\patent_claim_onlyabstract\csv1\\'
for file in os.listdir(dta_path):
    if not file.endswith('.dta'):
        continue
    data = pd.io.stata.read_stata(dta_path + file)
    file = file.replace('dta', 'csv')
    # utf-8_sig解决 pandas.to_csv()中文乱码问题
    data.to_csv(csv_path + file, encoding='utf-8_sig')

你可能感兴趣的:(python,java,开发语言,后端)