谁能帮助我并向我解释为什么我总是收到错误消息? 我有一个格式化为字典的字符串。类似下面:
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()
,但都失败了。我一直收到同样的错误。
有人可以向我解释我的代码或字符串有什么问题吗?
答案 0 :(得分:1)
您缺少正确的撇号:
根据大众需求,您也可以这样做:
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"}'
json.loads(str1_dict)
您也可以使用 eval,但要知道它可能不安全,应根据您的用例避免或谨慎使用:
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'}"
eval(str1_dict)
答案 1 :(得分:1)
问题是您的字符串不包含有效的 JSON。您可以使用此函数在字典中解析无效的 JSON:
def str2dict(data):
data = data.strip(" {}") # get rid of brackets and spaces at the start an end
key_value_pair_strings = data.split(",") # split data at , into key value pair strings
key_value_pair_strings_stripped = list(map(str.strip, key_value_pairs)) # strip whitespaces from the key value pair strings
key_value_pairs = list(map(lambda s: s.split(":"), key_value_pair_strings)) # get key value pairs by splitting each key value pair string at :
return dict(key_value_pairs)
result = str2dict("{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}")
print(result["Sentence"])
整个函数体可以缩减为一行!
def str2dict_one_line(data):
return dict(list(map(lambda s: s.split(":"), list(map(str.strip, data.strip(" {}").split(","))))))
result = str2dict_one_line("{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}")
print(result["Sentence"])