python中字符串到OrderedDict的转换

python中字符串到OrderedDict的转换,python,string,parsing,ordereddictionary,Python,String,Parsing,Ordereddictionary,我通过导入集合创建了一个python有序字典,并将其存储在名为“filename.txt”的文件中。文件内容如下所示 OrderedDict([(7, 0), (6, 1), (5, 2), (4, 3)]) 我需要利用从另一个项目订购的信息。我照你说的做 myfile = open('filename.txt','r') mydict = myfile.read() 我需要把“mydict”作为类型 <class 'collections.OrderedDict'> 但在

我通过导入集合创建了一个python有序字典,并将其存储在名为“filename.txt”的文件中。文件内容如下所示

OrderedDict([(7, 0), (6, 1), (5, 2), (4, 3)])
我需要利用从另一个项目订购的信息。我照你说的做

myfile = open('filename.txt','r')
mydict = myfile.read()
我需要把“mydict”作为类型

<class 'collections.OrderedDict'>

但在这里,它是“str”型的。

python中有没有办法将字符串类型转换为OrderedDict类型?使用python 2.7,您可以使用

将cPickle作为pickle导入
#商店:
打开(“filename.pickle”、“w”)作为fp:
pickle.dump(按顺序排列,fp)
#阅读:
将open(“filename.pickle”)作为fp:
有序存储=pickle.load(fp)
类型(按顺序排列)

这里的最佳解决方案是以不同的方式存储数据,比如说

您也可以使用其他答案中解释的方法,但这有潜在的安全问题(如下面的
eval()
所述)-因此,只有在您知道数据总是可信的情况下才使用此解决方案

如果您不能更改数据的格式,那么还有其他解决方案

真正糟糕的解决方案是用它来做这件事。这是一个非常非常的坏主意,因为它是不安全的,因为放入文件中的任何代码都将与

更好的解决方案是手动解析文件。好的一面是,有一种方法可以让你在这件事上作弊,而且做起来更容易一些。Python提供了一个可以轻松解析文本的工具。虽然这不是一个文本,因为它使用OrderedDict,但我们可以提取列表文本并解析它

例如:(未经测试)


这不是一个好的解决方案,但很有效。:)


下面是我如何在Python2.7上实现的

from collections import OrderedDict
from ast import literal_eval

# Read in string from text file
myfile = open('filename.txt','r')
file_str = myfile.read()

# Remove ordered dict syntax from string by indexing
file_str=file_str[13:]
file_str=file_str[:-2]

# convert string to list
file_list=literal_eval(file_str)

header=OrderedDict()
for entry in file_list:
    # Extract key and value from each tuple
    key, value=entry
    # Create entry in OrderedDict
    header[key]=value

同样,您可能应该以不同的方式编写文本文件

我对你的问题没有一个好的答案(即不使用
eval
),但你真的不应该这样存储它。不要那样存储数据。至少要用泡菜。我将否决任何建议使用
eval()
的答案人们害怕
eval
的原因本质上是宗教而非理性的。每一种语言结构的存在都有其原因,当一个
eval(x)
完成任务时,就不需要发明复杂的东西。是的,它应该谨慎使用(像其他任何东西一样),但只要数据来自可信的来源,使用
eval
就可以了。@thg435好吧,因为我们不知道数据是否来自可信的来源,这是迈出的一大步。即使是这样,当有很多更好的方法时,为什么还要使用丑陋、缓慢、潜在危险、难以调试的方法呢。这里真正的问题是数据是如何存储的,而以另一种格式存储数据还有其他好处(比如,如果您需要Python以外的格式的数据怎么办?。@Lattyware:eval争论已经厌倦了说最好的了。就像几十年前的“goto”一样,人们似乎对它产生了某种非理性的恐惧。我们中的大多数人认为它本身是邪恶的,并且相信只要写一次它就会给他们的代码甚至他们的生活带来永久的诅咒。这似乎是某种宗教,因此与计算机编程的理性世界无关。+1,如果有两件事的话将是+2:a)可能,b)更清楚地表明“真正糟糕的解决方案”实际上是“纯粹邪恶的”解决当前问题的好办法,我也在想同样的事情。@Cpfohl,c)如果+2为possible@gnibbler:参见
a
;-)。。。哎呀。。。语法错误1450模棱两可的语法分析有趣的是,你的评论恰恰相反,也就是说,eval没有错。请注意,pickle可能和eval一样危险。不要解开你无法解开的数据trust@gnibbler:+1提到泡菜是不安全的。另见:
import re
import ast
import collections

with open(filename.txt) as file:
    line = next(file)
    values = re.search(r"OrderedDict\((.*)\)", line).group(1)
    mydict = collections.OrderedDict(ast.literal_eval(values))
#######################################
# String_To_OrderedDict
# Convert String to OrderedDict
# Example String
#    txt = "OrderedDict([('width', '600'), ('height', '100'), ('left', '1250'), ('top', '980'), ('starttime', '4000'), ('stoptime', '8000'), ('startani', 'random'), ('zindex', '995'), ('type', 'text'), ('title', '#WXR#@TU@@Izmir@@brief_txt@'), ('backgroundcolor', 'N'), ('borderstyle', 'solid'), ('bordercolor', 'N'), ('fontsize', '35'), ('fontfamily', 'Ubuntu Mono'), ('textalign', 'right'), ('color', '#c99a16')])"
#######################################
def string_to_ordereddict(txt):

    from collections import OrderedDict
    import re

    tempDict = OrderedDict()

    od_start = "OrderedDict([";
    od_end = '])';

    first_index = txt.find(od_start)
    last_index = txt.rfind(od_end)

    new_txt = txt[first_index+len(od_start):last_index]

    pattern = r"(\(\'\S+\'\,\ \'\S+\'\))"
    all_variables = re.findall(pattern, new_txt)

    for str_variable in all_variables:
        data = str_variable.split("', '")
        key = data[0].replace("('", "")
        value = data[1].replace("')", "")
        #print "key : %s" % (key)
        #print "value : %s" % (value)
        tempDict[key] = value

    #print tempDict
    #print tempDict['title']

    return tempDict
from collections import OrderedDict
from ast import literal_eval

# Read in string from text file
myfile = open('filename.txt','r')
file_str = myfile.read()

# Remove ordered dict syntax from string by indexing
file_str=file_str[13:]
file_str=file_str[:-2]

# convert string to list
file_list=literal_eval(file_str)

header=OrderedDict()
for entry in file_list:
    # Extract key and value from each tuple
    key, value=entry
    # Create entry in OrderedDict
    header[key]=value