python - 使用 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:这是我要转换的文本文件
解决方案
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)
https://docs.google.com/spreadsheets/d/1gqE0KX0Qw1o7SBegv1riIHSczXhhZA4Ot2oYOaEKZN4/edit?usp=sharing
推荐阅读
- android - 如何将 Kotlin 协程与 onSuccessListner 一起使用?
- ios - 有时在 iOS Swift 上渲染粉色容器的图像资源
- laravel - 如何在 laravel 框架中编写以下 mapreduce mongodb 查询
- javascript - 正则表达式来选择特定的词
- visual-studio-2019 - 更改 Visual Studio 2019 的搜索引擎
- c++ - C ++,如果某些条目重复,则输出所有可能的排列(递归算法)
- windows - Powershell检查用户是否是本地用户并且具有本地Windows机器上的用户名和密码的管理员权限(非活动目录)
- java - SystemProperties 类方法的替代方法及其在 java 或 kotlin 中的用法是什么?
- reactjs - 列内的反应路由器链接不会“填充”整个列
- sql-server - 如何通过 EF 检索自定义/用户定义列的值?