TypeError: tuple indices must be integers or slices, not str Python sentiment tweet

TypeError: tuple indices must be integers or slices, not str Python sentiment tweet

我正在尝试捕捉真实的直播推文。我正在尝试使用 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

你的问题是 x 是元组,所以你需要使用像 x[1] 这样的数字索引,而不是字符串。

这里,

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

x 是你字典的元组 (key,value) 所以你必须传递索引。

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