【问题标题】:Python how to read orderedDict from a txt filePython如何从txt文件中读取orderedDict
【发布时间】:2016-04-22 06:14:21
【问题描述】:

基本上我想从文本文件中读取一个字符串并将其存储为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

【问题讨论】:

  • 文件从何而来?你能用更好的格式吗?
  • 当我尝试运行常规代码时出现语法错误
  • 不清楚你到底想输出什么 xxx_c -> xxx_d 不会出现在原始字符串中,yyy 不会出现在输出中你也有括号不匹配。但是,如果我是您,我会查看 execfile 并尝试使用这样的代码 from collections import OrderedDict ; v = {'OrderedDict':OrderedDict} ; execfile('1.txt', {}, v) ; print v(我假设您的文件名为 1.txt注意如果您不信任,调用 execfile 是危险的该文件的来源,例如它可以删除您计算机上的所有文件。

标签: python string ordereddictionary


【解决方案1】:
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)

输出:

variable_one
{
    "xxx": {
        "xxx_a": "xxx_b", 
        "xx_c": "xx_d"
    }, 
    "yyy": {
        "yyy_a": "yyy_b", 
        "yy_c": "yy_d"
    }
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-19
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多