我正在研究NLTK:
data = urllib.parse.urlencode({"text": "I'm good "}).encode('ascii')
u = urllib.request.urlopen("http://text-processing.com/api/sentiment/",data)
the_page = u.read()
print (the_page)
b'{"probability": {"neg": 0.22531846855219551, "neutral":
0.084284385065714951, "pos": 0.77468153144780449}, "label": "pos"}'
这显然是字节,我想将这个字节数组转换为字典来访问键“label”的值
d = dict(toks.split(":") for toks in the_page.decode("ascii").split(",") if
toks) #Error referred here
for key,value in d.items():
if key is 'label':
print (value)
#Should return pos
脚本抛出错误,“ValueError:字典更新序列元素#0的长度为3;需要2 “
答案 0 :(得分:3)
只需使用json
模块将其转换为常规Python字典:
import json
d = json.loads(the_page.decode("utf-8"))
print(d["label"])
希望这有帮助。