how to extract a text file into a dictionary

后端 未结 3 1553
自闭症患者
自闭症患者 2021-01-14 08:08

i am wondering how you would extract a text into dictionary in python. the text file is formatted as such(see below) and extract in way so that object earth for example is t

相关标签:
3条回答
  • 2021-01-14 09:01
    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
    

    output:

    {
        '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'
            }
        }
    
    0 讨论(0)
  • 2021-01-14 09:04

    Using a modification of one of the above you would get something like the following:

    def read_next_object(file):    
            obj = {}               
            for line in file:      
                    if not line.strip(): continue
                    line = line.strip()                        
                    key, val = line.split(": ")                
                    if key in obj and key == "Object": 
                            yield obj                       
                            obj = {}                              
                    obj[key] = val
    
            yield obj              
    planets = {}                   
    with open( "test.txt", 'r') as f:
            for obj in read_next_object(f): 
                    planets[obj["Object"]] = obj    
    
    print planets                  
    

    Fix the case for the RootObject and I believe this is the final dictionary that you are looking for from the example data that you have posted. It is a dictionary of planets where each planet is a dictionary of it's information.

    print planets["Sun"]["Radius"]
    

    Should print the value 20890260

    The output from the above looks like the following:

    {   'Earth': {   'Object': 'Earth',
                 'Orbital Radius': '77098290',
                 'Period': '365.256363004',
                 'Radius': '6371000.0',
                 'Satellites': 'Moon'},
         'Moon': {   'Object': 'Moon',
                'Orbital Radius': '18128500',
                'Period': '27.321582',
                'Radius': '1737000.10'},
         'Sun': {   'Object': 'Sun',
               'Orbital Radius': '0',
               'Radius': '20890260',
               'RootObject': 'Sun',
               'Satellites': 'Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune,Ceres,Pluto,Haumea,Makemake,Eris'}}
    
    0 讨论(0)
  • 2021-01-14 09:09

    Assuming you want elements with comma-separated values as lists, try:

    mydict={}
    with open(my_file,'r') as the_file:
        for line in the_file:
            if not line.strip(): continue # skip blank lines
            key,val=line.split(": ")
            val = val.split(",")
            mydict[key] = val if len(val) > 1 else val[0]
    
    0 讨论(0)
提交回复
热议问题