将字符串作为有序字典导入 [英] Importing string as an ordered dictionary

查看:63
本文介绍了将字符串作为有序字典导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个没有扩展名的文件,带有这样的行(忽略行之间的间距,但每一行都是单独的行):

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')])

当我将其导入Python

when I import it to Python

snap_fh = open("C:\Users\.......")
for row in snap_fh:
    print(type(row))

行是字符串" ,我无法将其解析为 OrderedDictionary

rows are "strings" and I cannot parse it as an OrderedDictionary

"OrderedDict([('key1', u'value1'), ('key2', 'value2'))])\n"

如何将其作为 OrderedDict

ast.literal_eval(row)无效!

推荐答案

您应使用正则表达式进行更安全的评估:

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)

这篇关于将字符串作为有序字典导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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