使用Big Huge Thesaurus API时出现Python错误

时间:2016-12-25 19:11:01

标签: python json

我在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")

请帮忙

1 个答案:

答案 0 :(得分:1)

您需要捕获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)))