0

我有一个文本文件,其中用户 ID 和推文文本由“-->”分隔。我想将这些加载到字典中,然后迭代这些值,使用 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'

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

4

1 回答 1

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'])
于 2016-01-10T15:07:38.297 回答