【问题标题】:Best way to read a text data file with key="value" format?读取具有 key="value" 格式的文本数据文件的最佳方法?
【发布时间】:2020-12-08 03:11:17
【问题描述】:

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

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

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

【问题讨论】:

标签: python text


【解决方案1】:

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

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

【讨论】:

  • 我遇到的主要问题是如何根据数据设置列名,特别是如果 Group 和 Quantity 在不同的行上交换。
  • @ElliottVentura -- 当你说“swapped”时,你的意思是线上物品的顺序会有所不同吗?换句话说,有时顺序是描述,然后是组,然后是数量,有时顺序是描述,然后是数量,然后是组?如果是这种情况,我可以尝试编辑我的解决方案来解决这个问题。这种情况可能涉及一次处理一行。
猜你喜欢
  • 2014-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多