首页 > 解决方案 > 读取具有 key="value" 格式的文本数据文件的最佳方法?

问题描述

我有一个格式如下的文本文件:

item(1) description="Tofu" Group="Foods" Quantity=5
item(2) description="Apples" Group="Foods" Quantity=10

在 Python 中阅读这种格式的最佳方式是什么?

标签: pythontext

解决方案


这是您可以在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

根据您要完成的工作以及您期望数据中有多少变化,可能有很多方法可以做到这一点。


推荐阅读