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

标签 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")

请帮忙

最佳答案

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

相关文章:

javascript - 如何在 Javascript 中将表单数组转换为 JSON? (对象数组)?

python - 为什么我的 Python 函数不将列转换为日期时间格式

python - PySpark - 将空值替换为相应行的平均值

PHP json 处理程序与旧的 php 版本兼容

java - 将具有不同对象的 json 数组解析为它们的类

java - 如何打印二叉树

java - JSON 中所选键的掩码值

python - pandas concat 用 NaN 填充非对齐索引

python - 在 Ruby 中加密字符串并在 Python 中解密

python - 如何在循环外使用循环计数