我正在用 python 构建一个同义词程序。 我有 API_KEY,我能够获取 JSON 输出
但是对于“ABRIGATE”等一些单词,我在终端上收到此错误
Traceback (most recent call last):
File "word_power.py", line 26, in <module>
json_obj = urllib2.urlopen(final_url)
File "/usr/lib/python2.7/urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 435, in open
response = meth(req, response)
File "/usr/lib/python2.7/urllib2.py", line 548, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python2.7/urllib2.py", line 473, in error
return self._call_chain(*args)
File "/usr/lib/python2.7/urllib2.py", line 407, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 556, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 404: Not Found
此外,使用 urlin 浏览器查找时,我会看到一个空白页面。
http://words.bighugelabs.com/api/2/------API_KEY------/abrigate/json
我想我无法检测 JSON 结果是否存在。
我正在检查的代码是:
json_obj = urllib2.urlopen(final_url)
data = json.load(json_obj)
if not data:
print 'Empty'
if 'noun' not in data:
print 'NO NOUN'
#target.write(" ]\n\n");
if 'verb' not in data:
print 'NO VERB'
#target.write(" ]\n\n")
if 'adjective' not in data:
print 'NO ADJECTIVE'
#target.write(" ]\n\n")
请帮忙
最佳答案
您需要捕获 API 返回错误的实例:
data = None
try:
json_obj = urllib2.urlopen(final_url)
data = json.load(json_obj)
except urllib2.HTTPError, e:
if e.code == '404':
print('Entry not found for URL {}'.format(final_url))
else:
print('Got {} - {} for URL {}.'.format(e.code, e.msg, final_url))
您还可以改进检查逻辑:
for key,value in data.items():
print('Word type is: {}'.format(key))
for prop, values in value.items():
print('\t{} : {}'.format(prop, ','.join(values)))
关于使用 Big Huge Thesaurus API 时出现 Python 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41323816/