簡體   English   中英

TypeError:元組索引必須是整數或切片,而不是str Python情緒鳴叫

[英]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

這里,

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

x是字典的(key,value)的元組,因此您必須傳遞索引。

如果您只是想要'text'鍵的數據。 你可以寫tweet['text']

您的問題是x是元組,因此您需要使用x[1]類的數字索引,而不是字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM