Python如何从txt文件中读取orderedDict

时间:2016-04-22 06:14:22

标签: python string ordereddictionary

基本上我想从文本文件中读取一个字符串并将其存储为orderedDict。 我的文件包含以下内容。

content.txt:

variable_one=OrderedDict([('xxx', [['xxx_a', 'xxx_b'],['xx_c', 'xx_d']]),('yyy', [['yyy_a', 'yyy_b'],['yy_c', 'yy_d']]))])

variable_two=OrderedDict([('xxx', [['xxx_a', 'xxx_b'],['xx_c', 'xx_d']]),('yyy', [['yyy_a', 'yyy_b'],['yy_c', 'yy_d']]))])

我将如何在python中检索值:

xxx 

   xxx_a -> xxx_b

   xxx_c -> xxx_d

1 个答案:

答案 0 :(得分:0)

function base64(buffer) {
    var binary = '';
    var bytes = new Uint8Array(buffer);
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
    }
    return window.btoa(binary);
}

验证它有效:

import re
from ast import literal_eval
from collections import OrderedDict

# This string is slightly different from your sample which had an extra bracket
line = "variable_one=OrderedDict([('xxx', [['xxx_a', 'xxx_b'],['xx_c', 'xx_d']]),('yyy', [['yyy_a', 'yyy_b'],['yy_c', 'yy_d']])])"
match = re.match(r'(\w+)\s*=\s*OrderedDict\((.+)\)\s*$', line)
variable, data = match.groups()

# This allows safe evaluation: data can only be a basic data structure
data = literal_eval(data)

data = [(key, OrderedDict(val)) for key, val in data]
data = OrderedDict(data)

输出:

print variable
import json
print json.dumps(data, indent=4)

说了这么多,你的要求很奇怪。如果您可以控制数据源,请使用支持顺序的实际序列化格式(因此不是JSON)。不要输出Python代码。