将文本转换为包含特定键和值的字典

时间:2012-11-21 17:12:32

标签: python dictionary quickdraw

  

可能重复:
  how to extract a text file into a dictionary

我有一个文本文件,我想在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

到目前为止,我的代码是

def file():
    file = open('smallsolar.txt', 'r')
    answer = {}
    text = file.readlines() 
    print(text)



text = file() 
print (text)

我不确定现在做什么。有什么想法吗?

2 个答案:

答案 0 :(得分:3)

answer = {} # initialize an empty dict
with open('path/to/file') as infile: # open the file for reading. Opening returns a "file" object, which we will call "infile"

    # iterate over the lines of the file ("for each line in the file")
    for line in infile:

        # "line" is a python string. Look up the documentation for str.strip(). 
        # It trims away the leading and trailing whitespaces
        line = line.strip()

        # if the line starts with "Object"
        if line.startswith('Object'):

            # we want the thing after the ":" 
            # so that we can use it as a key in "answer" later on
            obj = line.partition(":")[-1].strip()

        # if the line does not start with "Object" 
        # but the line starts with "Orbital Radius"
        elif line.startswith('Orbital Radius'):

            # get the thing after the ":". 
            # This is the orbital radius of the planetary body. 
            # We want to store that as an integer. So let's call int() on it
            rad = int(line.partition(":")[-1].strip())

            # now, add the orbital radius as the value of the planetary body in "answer"
            answer[obj] = rad

希望这有帮助

有时,如果您的文件(3.14等)中有十进制表示法(python-speak中的“浮点数”),则在其上调用int将失败。在这种情况下,请使用float()代替int()

答案 1 :(得分:1)

用一个字符串而不是readlines()读取文件,然后拆分为“\ n \ n”,这样你就会有一个项目列表,每个项目都描述你的对象。

然后你可能想要创建一个类似这样的类:

class SpaceObject:
  def __init__(self,string):
    #code here to parse the string

    self.name = name
    self.radius = radius
    #and so on...

然后您可以使用

创建此类对象的列表
#items is the list containing the list of strings describing the various items
l = map(lambda x: SpaceObject(x),items).

然后只需执行以下操作

d= {}
for i in l:
  d[i.name] = i