gpt4 book ai didi

python-2.7 - 打开一个文本文件,然后将内容存储到 python 2.7 中的嵌套字典中

转载 作者:行者123 更新时间:2023-12-03 12:34:15 26 4
gpt4 key购买 nike

我对 Python 和一般的计算语言还很陌生。我想打开一个文本文件,然后将其内容存储在嵌套字典中。到目前为止,这是我的代码:

inputfile = open("Proj 4.txt", "r")
for line in inputfile:
line = line.strip()
print line
NGC = {}

inputfile.close()

我知道我需要对字典使用添加操作,我只是不确定如何继续。这是文本文件的副本:

NGC0224
Name: Andromeda Galaxy
Messier: M31
Distance: 2900
Magnitude: 3.4
NGC6853
Name: Dumbbell Nebula
Messier: M27
Distance: 1.25
Magnitude: 7.4
NGC4826
Name: Black Eye Galaxy
Messier: M64
Distance: 19000
Magnitude: 8.5
NGC4254
Name: Coma Pinwheel Galaxy
Messier: M99
Distance: 60000
Brightness: 9.9 mag
NGC5457
Name: Pinwheel Galaxy
Messier: M101
Distance: 27000
Magnitude: 7.9
NGC4594
Name: Sombrero Galaxy
Messier: M104
Distance: 50000

最佳答案

with open(infilepath) as infile:
answer = {}
name = None
for line in infile:
line = line.strip()
if line.startswith("NGC"):
name = line
answer[name] = {}
else:
var, val = line.split(':', 1)
answer[name][var.strip()] = val.strip()

用你的文本文件输出:

>>> with open(infilepath) as infile:
... answer = {}
... name = None
... for line in infile:
... line = line.strip()
... if line.startswith("NGC"):
... name = line
... answer[name] = {}
... else:
... var, val = line.split(':', 1)
... answer[name][var.strip()] = val.strip()
...
>>> answer
{'NGC6853': {'Messier': 'M27', 'Magnitude': '7.4', 'Distance': '1.25', 'Name': 'Dumbbell Nebula'}, 'NGC4254': {'Brightness': '9.9 mag', 'Messier': 'M99', 'Distance': '60000', 'Name': 'Coma Pinwheel Galaxy'}, 'NGC4594': {'Messier': 'M104', 'Distance': '50000', 'Name': 'Sombrero Galaxy'}, 'NGC0224': {'Messier': 'M31', 'Magnitude': '3.4', 'Distance': '2900', 'Name': 'Andromeda Galaxy'}, 'NGC4826': {'Messier': 'M64', 'Magnitude': '8.5', 'Distance': '19000', 'Name': 'Black Eye Galaxy'}, 'NGC5457': {'Messier': 'M101', 'Magnitude': '7.9', 'Distance': '27000', 'Name': 'Pinwheel Galaxy'}}

关于python-2.7 - 打开一个文本文件,然后将内容存储到 python 2.7 中的嵌套字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19395350/

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