ValueError:字典更新顺序元素#0的长度为3; 2需要:NLTK
问题描述:
我的工作NLTK:ValueError:字典更新顺序元素#0的长度为3; 2需要: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"}'
这显然是字节,我想转换此字节数组字典的键“标签的访问值“
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需要 “
答
只需使用json
模块将其转换为一个常规的Python字典:
import json
d = json.loads(the_page.decode("utf-8"))
print(d["label"])
希望这有助于。
看起来像JSON。也许尝试使用['json'](https://docs.python.org/3/library/json.html)模块。 –