将文本转换成具有某些键和值的字典 [英] Convert text into a dictionary with certain keys and values

查看:136
本文介绍了将文本转换成具有某些键和值的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

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


我有一个文本文件,我想在python中将其更改为字典。文本文件如下。我希望把钥匙作为太阳,地球和月亮,然后将其作为轨道半径,周期等等,以便我可以将动画太阳系实现为quickdraw。

  RootObject:Sun 

对象:Sun
卫星:水星,金星,地球,火星,木星,土星,天王星,海王星,Ceres,冥王星,Haumea,Makemake,Eris
半径:20890260
轨道半径:0

对象:地球
轨道半径:77098290
期间:365.256363004
半径:6371000.0
卫星:月球

对象:月球
轨道半径:18128500
半径:1737000.10
期间: 27.321582

我的代码到目前为止是

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



text = file()
print(text)
/ pre>

我不知道现在该怎么办任何想法?

解决方案

  answer = {}#初始化一个空的dict 
打开('path / to / file')作为infile:#打开文件进行阅读。开始返回一个文件对象,我们称之为infile

#遍历文件的行(对于文件中的每一行)
for infile:

#line是一个python字符串。查找str.strip()的文档。
#它修剪了前导和尾随的空格
line = line.strip()

#如果行以Object开头
if line.startswith( 'object'):

#我们想要的东西在:
#之后,以便我们可以在
obj = line .partition(:)[ - 1] .strip()

#如果行不以Object开头
#,但行以轨道半径开头
elif line.startswith('Orbital Radius'):

#得到:之后的东西。
#这是行星体的轨道半径。
#我们要将其存储为一个整数。所以我们来调用int()
rad = int(line.partition(:)[ - 1] .strip())

#现在,添加轨道半径为行星体在答案中的值
答案[obj] = rad

希望这个帮助



有时,如果您的文件中有一个十进制数字(python-speak)中的数字( 3.14 等),调用 int 就会失败。在这种情况下,使用 float()而不是 int()


Possible Duplicate:
how to extract a text file into a dictionary

I have a text file where I would like to change it into a dictionary in python. The text file is as follows. Where I would like to have the keys as "sun" and "earth" and "moon" and then for the values the orbital radius, period and such so that I can implement an animation solar system into quickdraw.

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 code so far is

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



text = file() 
print (text)

I'm not sure what do now. Any ideas?

解决方案

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

Hope this helps

Sometimes, if you have a number in decimal notation ("floating point numbers" in python-speak) in your file (3.14, etc), calling int on it will fail. In this case, use float() instead of int()

这篇关于将文本转换成具有某些键和值的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆