簡體   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