gpt4 book ai didi

python - 使用 Pandas 提取配置文件(看起来像 K/V 但不是)

转载 作者:行者123 更新时间:2023-12-01 06:31:59 25 4
gpt4 key购买 nike

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

Models{
Model1{
Description = "xxxx"
Feature = "yyyy"
EventType = [
"Type1",
"Type2"]
}

Model2{
Description = "aaaa"
Feature = "bbbb"
EventType = [
"Type3",
"Type4"]
}
}

有没有办法将其转换为如下数据框?

|Model  | Description | Feature | EventType    | 
------------------------------------------------
|Model1 | xxxx | yyyy | Type1, Type2 |
|Model2 | aaaa | bbbb | Type3, Type4 |

最佳答案

首先您应该将其转换为标准 JSON 格式。您可以使用正则表达式来完成此操作:

with open('untitled.txt') as f:
data = f.read()

import re
# Converting into JSON format
data = re.sub(r'(=\s*".*")\n', r'\1,\n', data)
data = re.sub(r'(Description|Feature|EventType)', r'"\1"', data)
data = re.sub(r'}(\s*Model[0-9]+)', r'},\1', data)
data = re.sub(r'(Model[0-9]+)', r'"\1"=', data)
data = re.sub(r'(Models)', r'', data)
data = re.sub(r'=', r':', data)

您的文件将如下所示:

{
"Model1":{
"Description" : "xxxx",
"Feature" : "yyyy",
"EventType" : [
"Type1",
"Type2"]
},

"Model2":{
"Description" : "aaaa",
"Feature" : "bbbb",
"EventType" : [
"Type3",
"Type4"]
}
}

然后,使用pd.read_json读取它:

import pandas as pd
from io import StringIO

df = pd.read_json(StringIO(data), orient='index').reset_index()
# index Description EventType Feature
#0 Model1 xxxx [Type1, Type2] yyyy
#1 Model2 aaaa [Type3, Type4] bbbb

关于python - 使用 Pandas 提取配置文件(看起来像 K/V 但不是),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59861602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com