简体   繁体   English

如何解析字典形式的文本文件并将其放入python字典中?

[英]How do I parse a text file in dictionary form and put it into a dictionary in python?

I want to take a text file that contains something of the form: 我想获取一个包含以下形式的文本文件:

{('q0','a'):('q0','a','R'),
('q0','b'):('q0','a','R'),
('q1',' '):('q1',' ','L')}

and place it into a real dictionary. 并将其放入真实的字典中 I've been hacking away at this for hours and have gotten very far. 我已经花了好几个小时来解决这个问题,并且已经走得很远了。 I think the solution is simple but I have found nothing useful on the internet. 我认为解决方案很简单,但是我发现互联网上没有任何用处。 Any help would be appreciated. 任何帮助,将不胜感激。

>>> ast.literal_eval('''{('q0','a'):('q0','a','R'),
... ('q0','b'):('q0','a','R'),
... ('q1',' '):('q1',' ','L')}
... ''')
{('q1', ' '): ('q1', ' ', 'L'), ('q0', 'a'): ('q0', 'a', 'R'), ('q0', 'b'):
  ('q0', 'a', 'R')}

If the file contains valid Python code describing a dictionary, just use eval : 如果文件包含描述字典的有效Python代码,请使用eval

>>> value = "{('q0','a'):('q0','a','R'),('q0','b'):('q0','a','R'),('q1',' '):('q1',' ','L')}"
>>> value
"{('q0','a'):('q0','a','R'),('q0','b'):('q0','a','R'),('q1',' '):('q1',' ','L')}"
>>> d = eval(value)
>>> type(d)
<type 'dict'>
>>> d
{('q1', ' '): ('q1', ' ', 'L'), ('q0', 'a'): ('q0', 'a', 'R'), ('q0', 'b'): ('q0', 'a', 'R')}

However, I wouldn't recommend this method of passing information around (between Python programs, say). 但是,我不建议这种在(Python程序之间)传递信息的方法。 For that I would use something like pickle, or perhaps json serialization, depending on the exact needs. 为此,我将使用pickle之类的东西,或者根据实际需要使用json序列化。

Try using exec statement: 尝试使用exec语句:

>>> d="""{('q0','a'):('q0','a','R'),
... ('q0','b'):('q0','a','R'),
... ('q1',' '):('q1',' ','L')}"""
>>> exec("myDict=%s" % d)
>>> myDict
{('q1', ' '): ('q1', ' ', 'L'), ('q0', 'a'): ('q0', 'a', 'R'), ('q0', 'b'): ('q0
', 'a', 'R')}
>>>

The easy way to do what you want is by using eval statement. 执行所需操作的简单方法是使用eval语句。 However, if the file gets tampered, it may cause security problems. 但是,如果文件被篡改,则可能会导致安全问题。 I'd highly reccomend using Pickle to store your dictionaries into a file. 我强烈建议您使用Pickle将您的词典存储到文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM