gpt4 book ai didi

python - 如何将文本文件提取到字典中

转载 作者:太空宇宙 更新时间:2023-11-03 13:48:59 25 4
gpt4 key购买 nike

我想知道如何在 Python 中将文本提取到字典中。文本文件的格式是这样的(见下文)并以某种方式提取,例如地球是关键,它的半径、周期和所有都在它的关键内。

RootObject: Sun

Object: Sun

Satellites: Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune,Ceres,Pluto,Haumea,Makemake,Eris

Radius: 20890260

Orbital Radius: 0

Object: Earth

Orbital Radius: 77098290

Period: 365.256363004

Radius: 6371000.0

Satellites: Moon

Object: Moon

Orbital Radius: 18128500

Radius: 1737000.10

Period: 27.321582

最佳答案

nk="""
RootObject: Sun

Object: Sun
Satellites: Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune,Ceres,Pluto,Haumea,Makemake,Eris
Radius: 20890260
Orbital Radius: 0

Object: Earth
Orbital Radius: 77098290
Period: 365.256363004
Radius: 6371000.0
Satellites: Moon

Object: Moon
Orbital Radius: 18128500
Radius: 1737000.10
Period: 27.321582

"""

my_test_dict={}
for x in nk.splitlines():
if ':' in x:
if x.split(':')[0].strip()=='RootObject':
root_obj=x.split(':')[1].strip()
elif x.split(':')[0].strip()=='Object':
my_test_dict[x.split(':')[1].strip()]={}
current_dict=x.split(':')[1].strip()
if x.split(':')[1].strip()!=root_obj:
for x1 in my_test_dict:
if 'Satellites' in my_test_dict[x1]:
if x.split(':')[1].strip() in my_test_dict[x1]['Satellites'].split(','):
my_test_dict[x.split(':')[1].strip()]['RootObject']=x1
else:
my_test_dict[current_dict][x.split(':')[0].strip()]=x.split(':')[1].strip()

print my_test_dict

输出:

{
'Sun':
{
'Satellites': 'Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune,Ceres,Pluto,Haumea,Makemake,Eris',
'Orbital Radius': '0',
'Radius': '20890260'
},

'Moon':
{
'Orbital Radius': '18128500',
'Radius': '1737000.10',
'Period': '27.321582',
'RootObject': 'Earth'
},

'Earth':
{
'Satellites': 'Moon',
'Orbital Radius': '77098290',
'Radius': '6371000.0',
'Period': '365.256363004',
'RootObject': 'Sun'
}
}

关于python - 如何将文本文件提取到字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13486203/

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