【发布时间】: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