问题
I have a file with no extension with lines like this (ignore the spacing between the lines, but each line is a separate row):
OrderedDict([('key1', u'value1'), ('key2', 'value2')])
OrderedDict([('key1', u'value1'), ('key2', 'value2')])
OrderedDict([('key1', u'value1'), ('key2', 'value2')])
when I import it to Python
snap_fh = open("C:\Users\.......")
for row in snap_fh:
print(type(row))
rows are "strings"
and I cannot parse it as an OrderedDictionary
"OrderedDict([('key1', u'value1'), ('key2', 'value2'))])\n"
How can I import it as an OrderedDict
ast.literal_eval(row)
did not work !
回答1:
You should use a regular expression for safer evaluation:
import re
import ast
from collections import OrderedDict
def read(f):
for s in f:
m = re.match(r'^OrderedDict\((.+)\)$', s)
if m:
yield OrderedDict(ast.literal_eval(m.group(1)))
...
for d in read(snap_fh):
print type(d)
回答2:
Using eval seems to work nicely
s = "OrderedDict([('key1', u'value1'), ('key2', 'value2')])"
a = eval(s, {'OrderedDict': OrderedDict})
print (a)
Use it only if you trust the source of your inputs - since eval is very risky
来源:https://stackoverflow.com/questions/34797928/importing-string-as-an-ordered-dictionary