TypeError:元组索引必须是整数或切片,而不是str Python情绪推文

时间:2017-03-23 12:42:58

标签: python json tweepy sentiment-analysis urllib3

我正在尝试捕捉真实的现场推文。我正在尝试使用json库访问内容,并创建新对象并将其附加到列表中。

from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import tweepy

import json
import urllib.parse
from urllib.request import urlopen
import json

# Variables that contains the user credentials to access Twitter API
consumer_key = ""
consumer_secret = "C"
access_token = ""
access_token_secret = ""
sentDexAuth = ''


auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)



def sentimentAnalysis(text):
    encoded_text = urllib.parse.quote(text)
    API_Call = 'http://sentdex.com/api/api.php?text=' + encoded_text + '&auth=' + sentDexAuth
    output = urlopen(API_Call).read()

    return output

class StdOutListener(StreamListener):
    def __init___(self):
        self.tweet_data = []


def on_data(self, data):
    tweet = json.loads(data)
    for x in tweet.items():
        sentimentRating = sentimentAnalysis(x['text'])
        actualtweets = {
            'created_at' : x['created_at'],
            'id' : x['id'],
            'tweets': x['text'] + sentimentRating
        }
        self.tweet_data.append(actualtweets)


    with open('rawtweets2.json', 'w') as out:
        json.dump(self.tweet_data, out)

    print(tweet)
l = StdOutListener()
stream = Stream(auth, l)
keywords = ['iknow']
stream.filter(track=keywords)

我相信我正确访问json对象但是我不确定这个错误,我需要它是一个字符串让我的情绪函数工作,并且 我得到一个类型错误:

sentimentRating = sentimentAnalysis(x['text'])
TypeError: tuple indices must be integers or slices, not str

2 个答案:

答案 0 :(得分:2)

下面,

for x in tweet.items():
        sentimentRating = sentimentAnalysis(x['text'])

x是您词典(key,value)的元组,因此您必须传递索引。

如果您只想要'text'键的数据。你可以写tweet['text']

答案 1 :(得分:0)

您的问题是x是元组,因此您需要使用x[1]之类的数字索引,而不是字符串。