谁能帮我解释一下为什么我总是出错? 我有一个格式化为字典的字符串。与以下内容类似:
str1_dict="{Sentence:Frequently Asked Questions AND PRIVACY ,Question:What is the most frequently asked question about privacy?,Answer0:Frequently,Question:What does Privacy stand for?,Answer1:PRIVACY}"
我实现了一个函数,它接受str1_dict
并返回一个值(例如,键"Sentence."
的值)
每次在字符串str1_dict
上运行此函数时,都会出现以下错误:
File "<string>", line 1
{Sentence:Frequently Asked Questions AND PRIVACY ,Question:What is the most frequently asked question about privacy?,Answer0:Frequently,Question:What does Privacy stand for?,Answer1:PRIVACY}
^
SyntaxError: invalid syntax
这是我的密码:
import json
str1_dict="{Sentence:Frequently Asked Questions AND PRIVACY ,Question:What is the most frequently asked question about privacy?,Answer0:Frequently,Question:What does Privacy stand for?,Answer1:PRIVACY}"
def Read_dict(Data):
line_tmp= Data.replace('\n','')
jsn = eval(line_tmp)
#jsn = json.loads(line_tmp)
#jsn= ast.literal_eval(line_tmp)
return jsn['Sentence']
Read_dict(str1_dict)
我尝试了在网上找到的所有将字符串转换为字典的方法,如eval()
、json.loads()
、和ast.literal_eval()
,但都失败了。我总是犯同样的错误
有人能解释一下我的代码或字符串有什么问题吗
问题是您的字符串不包含有效的JSON。您可以使用此函数在字典中解析无效的JSON:
整个功能体可以减少到一行
您缺少正确的撇号:
根据大众需求,您也可以这样做:
您也可以使用eval,但要知道它可能不安全,应根据您的用例避免或谨慎使用:
相关问题 更多 >
编程相关推荐