0
我有一個由「 - >」分隔的userID和tweet文本的文本文件。我想將這些加載到字典中,然後迭代這些值,使用AlchemyAPI計算每條推文的情緒。 我輸入的數據與此類似(真正的文件擁有數百萬的記錄):KeyError:在Python中使用AlchemyAPI進行情感分析的'docSentiment'
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'[email protected]]+", '', 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'
我不不明白我做錯了什麼。任何人都可以幫忙嗎?
我不確定有什麼問題,但一個好的開始就是打印出「response」的內容來查看你回來的內容。可能由於某種原因,請求不起作用,並且響應可能包含有關出錯的信息。 –