I am a complete newbie to Python.
I have data in the following format :
ontology = {
'OBJECT' :
{'IS-A' : {'VALUE' :'ALL'},
'SUBCLASSES' : {'VALUE' :['PHYSICAL-OBJECT',
'MENTAL-OBJECT','SOCIAL-OBJECT']},
'THEME-OF' : {'sem' : 'EVENT'}},
'PHYSICAL-OBJECT' :
{'IS-A' : {'VALUE' :'OBJECT'},
'SUBCLASSES' : {'VALUE' :['ANIMATE', 'INANIMATE']},
'THEME-OF' : {'sem' : 'EVENT'}},
}
I want to load all this data into a Python dictionary. But I get an error if I used the eval(file.read()).
Is there any way I can do this? (I don't have any class definitions)
Eval is generally a bad plan for security reasons, and you'd be better serialising with pickle or JSON.
But it won't read because you can't assign variables with = using eval(). If that's the exact format, you could try skipping after the = and eval()ing the rest:
data = open('data.txt').read()
ontology = eval(data[data.find('=')+1:])
Using eval is a really bad idea . Use ast.literal_eval instead.
For that to work, you must get rid of ontology =
part, it's not needed. Leave only a dictionary itself in a file.
Then, load it as follows:
>>> import ast
>>> with open('data.txt') as file:
... data = ast.literal_eval(file.read())
...
>>> data
{'PHYSICAL-OBJECT': {'IS-A': {'VALUE': 'OBJECT'}, 'THEME-OF': {'sem': 'EVENT'}, 'SUBCLASSES': {'VALUE': ['ANIMATE', 'INANIMATE']}}, 'OBJECT': {'IS-A': {'VALUE': 'ALL'}, 'THEME-OF': {'sem': 'EVENT'}, 'SUBCLASSES': {'VALUE': ['PHYSICAL-OBJECT', 'MENTAL-OBJECT', 'SOCIAL-OBJECT']}}}
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.