1

我正在尝试使用 Python 从 Sentiment140 API 请求数据。API 使用批量分类服务 (JSON)。在终端内它工作正常

curl -d "{'data': [{'text': 'I love Titanic.'}, {'text': 'I hate Titanic.'}]}" http://www.sentiment140.com/api/bulkClassifyJson

导致以下响应:

{"data":[{"text":"I love Titanic.","polarity":4,"meta":{"language":"en"}},{"text":"I hate Titanic.","polarity":0,"meta":{"language":"en"}}]}

我以为我可以使用 urllib 从我的 python 代码中获得相同的响应。我试过了:

import urllib
import urllib2

url = 'http://www.sentiment140.com/api/bulkClassifyJson'
values = {'data': [{'text': 'I love Titanic.'}, {'text': 'I hate Titanic.'}]}

data = urllib.urlencode(values)
response = urllib2.urlopen(url, data)
page = response.read()

该代码有效,但没有给我任何结果。我错过了什么吗?

4

1 回答 1

4

我认为您需要在这里使用 json 。

试着做:

data = json.dumps(values) # instead of urllib.urlencode(values)
response = urllib2.urlopen(url, data)
page = response.read()

并在顶部

import json 
于 2013-07-09T09:49:45.403 回答