问题描述
我正在尝试从文件中读取字典,然后将字符串变成字典.我有这个,
I'm trying to read a dictionary off a file and then make the string into a dictionary. I have this,
with open("../resources/enemyStats.txt", "r") as stats:
for line in stats:
if self.kind in line:
line = line.replace(self.kind + " ", "")
line = dict(line)
return line
和txt文件中的行是
slime {'hp':5,'speed':1}
我希望能够返回一个字典,以便我可以轻松访问敌方角色的hp和其他值.
I'd like to be able to return a dict so that I can easily access the hp and other values for the enemy character.
推荐答案
dict()
不会解析Python字典文字语法;它不会接受字符串并解释其内容.它只能使用另一本字典或键值对序列,而您的行不符合这些条件.
dict()
does not parse Python dictionary literal syntax; it won't take a string and interpret its contents. It can only take another dictionary or a sequence of key-value pairs, your line doesn't match those criteria.
您需要使用 ast.literal_eval()
函数代替这里:
You'll need to use the ast.literal_eval()
function instead here:
from ast import literal_eval
if line.startswith(self.kind):
line = line[len(self.kind) + 1:]
return literal_eval(line)
我也对self.kind
的检测进行了一些调整;我假设如果要在行的开头找到self.kind
,则希望与之匹配.
I've also adjusted the detection of self.kind
a little; I'm assuming you wanted to match it if self.kind
is found at the start of the line.
这篇关于ValueError:字典更新序列元素#0的长度为1;从文件读取时需要2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!