我有這段代碼來閱讀python 2中的Mashape.com API。我如何在python 3中閱讀它?使用urllib閱讀mashabe API
代碼
import urllib, urllib2, json
from pprint import pprint
URL = "https://getsentiment.p.mashape.com/"
text = "The food was great, but the service was slow."
params = {'text': text, 'domain': 'retail', 'terms': 1, 'categories': 1,'sentiment': 1, 'annotate': 1}
headers = {'X-Mashape-Key': YOUR_MASHAPE_KEY}
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request(URL, urllib.urlencode(params), headers=headers)
response = opener.open(request)
opener.close()
data = json.loads(response.read())
pprint(data)
我想這代碼,但它有以下錯誤:
import urllib.parse
import urllib.request
URL = "https://getsentiment.p.mashape.com/"
text = "The food was great, but the service was slow."
params = {'text': text, 'domain': 'retail', 'terms': 1, 'categories': 1, 'sentiment': 1, 'annotate': 1}
headers = {'X-Mashape-Key': YOUR_MASHAPE_KEY}
opener = urllib.request.build_opener(urllib.request.HTTPHandler)
request = urllib.request.Request(URL, urllib.parse.urlencode(params), headers)
response = opener.open(request)
opener.close()
data = json.loads(response.read())
print(data)
錯誤:
TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str.
發表你與蟒蛇具有3,爲什麼你不能「閱讀」 –
我不知道如何讀它的問題,我從什麼地方複製這些代碼,我沒有找到這樣的事情python 3 – Scott
是的,但是當你用python 3運行這個代碼會發生什麼? –