当尝试迭代使用OpenCalais获得的Python dict时,得到一个KeyError

2024-04-24 03:42:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用OpenCalais标记内容。以下是我使用与API通信的代码:

import httplib2
import json
import ast

# Some local values needed for the call
LOCAL_API_KEY = '***********************' # Aquire this by registering at the Calais site
CALAIS_TAG_API = 'https://api.thomsonreuters.com/permid/calais'

# Some sample text from a news story to pass to Calais for analysis
test_body = 'Samsung is closing its Milk Music streaming service'

# header information need by Calais.
# For more info see http://www.opencalais.com/documentation/calais-web-service-api/api-invocation/rest
headers = {
    'X-AG-Access-Token': LOCAL_API_KEY,
    'Content-Type': 'text/raw',
    'outputFormat': 'application/json',
}

# Create your http object
http = httplib2.Http()
# Make the http post request, passing the body and headers as needed.
response, content = http.request(CALAIS_TAG_API, 'POST', headers=headers, body=test_body)

jcontent = json.loads(content) # Parse the json return into a python dict
output = json.dumps(jcontent, indent=4) # Pretty print the resulting dictionary returned.
print output

总之,这很好地工作,因为我能够得到以下输出(打印输出)。在

^{pr2}$

我注意到这些键都是超链接。总之,我想打印输出中的所有socialTags。为此,我编写了以下代码:

# Print all the social tags
for key, value in ast.literal_eval(output).items():
    if value["_typeGroup"] == 'socialTag':
        print value["name"]

但是,我得到一个错误:

Traceback (most recent call last):
  File "opencal.py", line 30, in <module>
    if value["_typeGroup"] == 'socialTag':
KeyError: '_typeGroup'

这个错误是什么?更准确的方法是什么?谢谢。在


Tags: the代码importapijsonhttpforoutput