繁体   English   中英

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

[英]KeyError: 'docSentiment' for sentiment analysis using AlchemyAPI in Python

我有一个文本文件,其中的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'

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

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

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'])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM