【问题标题】:Converting a string into a dictionary using literal_eval使用 literal_eval 将字符串转换为字典
【发布时间】:2014-06-03 13:48:48
【问题描述】:

该程序的整个想法是从文本文件中读取数据(使用“for”循环从字典中保存为字符串),然后将该内容插入到字典中。 之后,程序继续要求输入(姓名和号码)并将其添加到字典中。

我使用“ast.literal_eval”将字符串转换为字典,如下所示:

import ast

f = open("resources/contacts.txt", "r+")
contactlist = f.read() # converting the string into a dictionary starts here
contactlist = ast.literal_eval(contactlist) # and ends here
print(contactlist) # for debugging purposes 

answer = 'again'

while answer == 'again':
    contact = input("enter a contact name: ")
    contactnum = input("enter the contact's number: ")
    contactlist[contact]= contactnum
    answer = input("again or stop: ")

f = open("resources/contacts.txt", "r+")

for item in contactlist:
    f.write(item + contactlist[item])

print(f.read())
f.close()

这会引发错误:

Traceback (most recent call last):
  File "D:\Code\Python\Projects\Contacts.py", line 5, in <module>
    contactlist = ast.literal_eval(contactlist)
  File "D:\Code\Python\PYTHON\lib\ast.py", line 84, in literal_eval
    return _convert(node_or_string)
  File "D:\Code\Python\PYTHON\lib\ast.py", line 83, in _convert
raise ValueError('malformed node or string: ' + repr(node))
ValueError: malformed node or string: <_ast.Name object at 0x02F52B10>

从我发现的这个错误来看,它不接受任何超出特定范围的值类型,但我的应该被接受。 我迷路了,我已经搜索了几十个相关线程,但找不到解决方法。

【问题讨论】:

  • print(contactlist) 带给你什么?
  • @jonrsharpe 如果我删除第 4 行,它会打印:Name00000000
  • 那么你希望ast.literal_eval 怎么解释呢?!那不是字典的字符串表示!
  • @jonrsharpe 我不知道..这是我能找到的唯一可以做我想做的事情的方法,我可能已经脱离了球场。
  • 我想我应该重新表述我的问题,字典的字符串表示形式是什么样的?

标签: python string dictionary


【解决方案1】:

你有一本像这样的字典:

{'Name': '00000000'}

当你写出来时:

for item in contactlist:
    f.write(item + contactlist[item])

您的文件是:

Name00000000

你不能用ast.literal_eval解析它——它不再“看起来像”一个Python字典。相反,写出整个字典的字符串表示:

f.write(str(contactlist))

那么你的文件内容实际上看起来就像一本字典:

{'Name': '00000000'}

您可以将其评估回​​字典。

或者,查看例如pickle,可以创建任意 Python 数据结构的平面文件表示,或 json,可以处理例如整数、字符串和浮点数的列表和字典。

【讨论】:

  • 这很有道理,我忽略了很多次。非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-25
  • 1970-01-01
相关资源
最近更新 更多