简体   繁体   中英

convert text file into dictionary of dictionaries

I am having issues I have seen problem converting text files into a dictionary, but I think the issue is that the text file is a dictionary of dictionaries which I cannot seem to find a solution for.

Code:

# importing the module
import ast

# reading the data from the file
with open('emoji_data.txt', encoding="utf8") as f:
    data = f.read()
print("Data type before reconstruction : ", type(data))
data = ast.literal_eval(data)
print("Data type before reconstruction : ", type(data))

Error:

ValueError: malformed node or string: <ast.Name object at 0x0000020FBD4345E0>

.txt File:

EMOJI_DATA = {
    u'\U0001F947': { # 🥇
        'en' : ':1st_place_medal:',
        'status' : fully_qualified,
        'E' : 3,
        'de': ':goldmedaille:',
        'es': ':medalla_de_oro:',
        'fr': u':médaille_d’or:',
        'pt': ':medalha_de_ouro:',
        'it': u':medaglia_d’oro:',
        'fa': u':مدال_طلا:'
    },
    u'\U0001F948': { # 🥈
        'en' : ':2nd_place_medal:',
        'status' : fully_qualified,
        'E' : 3,
        'de': ':silbermedaille:',
        'es': ':medalla_de_plata:',
        'fr': u':médaille_d’argent:',
        'pt': ':medalha_de_prata:',
        'it': u':medaglia_d’argento:',
        'fa': u':مدال_نقره:'
    },
    u'\U0001F949': { # 🥉
        'en' : ':3rd_place_medal:',
        'status' : fully_qualified,
        'E' : 3,
        'de': ':bronzemedaille:',
        'es': ':medalla_de_bronce:',
        'fr': u':médaille_de_bronze:',
        'pt': ':medalha_de_bronze:',
        'it': ':medaglia_di_bronzo:',
        'fa': u':مدال_برنز:'
    },

A couple of comments looking at the text file:

  1. If the text file you included captures all the text, then the last line needs to end in another '}', not a comma.

  2. ast.literal_eval() does not work with python variable aliases.The text file includes this 'fully_qualified' alias:

 u'\U0001F947': { # 🥇
        'en' : ':1st_place_medal:',
        'status' : fully_qualified,

This variable alias won't work with ast.literal_eval().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM