KeyError:'docSentiment'用于在Python中使用AlchemyAPI进行情感分析

时间:2015-12-15 19:46:04

标签: python alchemyapi

我有一个文本文件,其中userID和tweet文本用“ - >”分隔。我想将这些加载到字典中然后迭代值,使用AlchemyAPI计算每条推文的情绪。 我的输入数据与此类似(真实文件有数百万条记录):

v2cigs --> New #ecig #regulations in #Texas mean additional shipping charges for residents. https:\/\/t.co\/aN3O5UfGUM #vape #ecigs #vapeon #vaporizer
JessyQuil --> FK SHIPPING I DON'T WANT TO WAIT TO BUY MY VAPE STUFF
thebeeofficial --> #Lancashire welcomes latest #ECIG law READ MORE: https:\/\/t.co\/qv6foghaOL https:\/\/t.co\/vYiTAQ6VED
2br --> #Lancashire welcomes latest #ECIG law READ MORE: https:\/\/t.co\/ghRWTxQy8r https:\/\/t.co\/dKh9TLkNRe

我的代码是:

import re
from alchemyapi import AlchemyAPI
alchemyapi = AlchemyAPI()

outputFile = ("intermediate.txt", "w")
tid =  1; #counter for keys in dictionary
tdict = {}  #dictionary to store tweet data
with open("testData.txt", "r") as inputfile :
    for lines in inputfile:
        tweets = lines.split("-->")[1].lstrip()
        tweets = re.sub("[^A-Za-z0-9#\s'.@]+", '', tweets)
        tdict[tid] = tweets.strip("\n")
        tid+=1

for k in tdict:
    response = alchemyapi.sentiment("text", str(tdict[k]))
    sentiment = response["docSentiment"]["type"]
    print sentiment

我收到错误:

sentiment = response["docSentiment"]["type"]
KeyError: 'docSentiment'

我不明白我做错了什么。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

在尝试访问密钥之前,您需要检查响应是否成功。

for k in tdict:
    response = alchemyapi.sentiment("text", str(tdict[k]))
    status = response.get('status')
    if status == 'ERROR':
        print(response['statusInfo'])
    else:
        print(response['docSentiment']['type'])