python - 读取具有 key="value" 格式的文本数据文件的最佳方法?
问题描述
我有一个格式如下的文本文件:
item(1) description="Tofu" Group="Foods" Quantity=5
item(2) description="Apples" Group="Foods" Quantity=10
在 Python 中阅读这种格式的最佳方式是什么?
解决方案
这是您可以在pandas中执行此操作以获取项目的 DataFrame 的一种方法。
(出于测试目的,我将您的文本文件复制粘贴到“test.txt”中。)
此方法自动分配列名并将列设置item(...)
为索引。您也可以手动分配列名,这会稍微改变脚本。
import pandas as pd
# read in the data
df = pd.read_csv("test.txt", delimiter=" ", header=None)
# set the index as the first column
df = df.set_index(0)
# capture our column names, to rename columns
column_names = []
# for each column...
for col in df.columns:
# extract the column name
col_name = df[col].str.split("=").str[0].unique()[0]
column_names.append(col_name)
# extract the data
col_data = df[col].str.split("=").str[1]
# optional: remove the double quotes
try:
col_data = col_data.replace('"', "")
except:
pass
# store just the data back in the column
df[col] = col_data
# store our new column names
df.columns = column_names
根据您要完成的工作以及您期望数据中有多少变化,可能有很多方法可以做到这一点。
推荐阅读
- php - 刀片模板 - @extends 和 @section 不起作用
- android - 如果我已经添加了 Google Maven 存储库,如何在 Android Studio 中修复此错误?
- python - 根据选择django从数据库中获取数据
- java - 在片段布局上遇到谷歌地图问题
- mysql - 如何将数据框保存到包含 json 格式数据的 sql server 中
- flutter - 如何一键删除所有列表项
- automated-tests - 使用 testcafe 运行器时的 TestCafe BrowserStack 环境问题
- jboss7.x - JBoss EAP 7.1.0.GA + picketlink 2.7.1.Final 导致 org.jboss.modules.ModuleLoadError
- angular - 使用 chartjs 和 firebase realtime db 创建实时折线图
- sql-server - 尝试使用平面文件导入在 MSSQL 中创建表时出错