3

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

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

inputfile.close()

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

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
4

2 回答 2

2
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'}}
于 2013-10-16T04:55:58.740 回答
0

您必须更好地定义您希望如何将此数据映射到字典。我可以更改文件格式,最好将其重新格式化为标准 INI 文件。您可以使用ConfigParser模块阅读它。

但如果你真的想走这条路。这是一个快速而肮脏的解决方案:

d = {}
k = ''
for line in open('Proj 4.txt'):
    if ':' in line:
        key, value = line.split(':', 1)
        d[k][key] = value.strip()
    else:
        k = line.strip()
        d[k] = {}

dict d 具有已解析的文件。

于 2013-10-16T04:54:03.207 回答