首页 > 解决方案 > 使用 python 将 .txt 文件转换为 .csv 文件

问题描述

在此处输入图像描述AR = 0.9995 N2 = 0.000 HE = 0.000
KR = 0.000 H2 = 6.3998E-08 H = 4.2639E-15 H2O = 0.000 CO2 = 0.000 CO = 0.000
CH4 = 6.6510E-08 CH3 = 8.0334E-10 CH2 = 6.7005E-12

我的文本文件采用这种形式,我想将其转换为 csv 文件,其中物种的名称在一行中,相应的数字在一行中,我非常感谢任何帮助。

在此处输入图像描述

https://drive.google.com/folderview?id=15MK_sRDOuYD9dTX_2FMmCK7Mdvc9CMfn:这是我要转换的文本文件

标签: python

解决方案


I transformed the file into a row, as mentioned in question

import re
import pandas as pd
#read the file from a txt
#list of files
list_files = ['data1.txt','data2.txt']
for j in list_files:
    f = open(j, "r")
    data = f.readlines()
    # joining the text and removing newline and space
    string = " ".join(data)
    string = " ".join(re.sub(r'[\n]', '', string).split())
    string = string.replace(' = ', '|').replace('= ', '|')
    data = {}
    list_string = string.split(" ")
    for i in list_string:
        k = i.split("|")
        print(k)
        data[k[0]] = float(k[1])
    f.close()
    df = pd.DataFrame([data])
    df.to_csv(f"{j.split('.txt')[0]}.csv", index=False)

enter image description here

https://docs.google.com/spreadsheets/d/1gqE0KX0Qw1o7SBegv1riIHSczXhhZA4Ot2oYOaEKZN4/edit?usp=sharing


推荐阅读