[英]TypeError: tuple indices must be integers or slices, not str Python sentiment tweet
I am trying to capture real live tweets. 我正在尝试捕捉真实的实时推文。 I am trying to access contents using the json library, and create new objects and append this into a list.
我正在尝试使用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)
I believe that i am accessing the json objects correctly however i am not sure of this error, i need it to be a string for my sentiment function to work, and iam getting a type error: 我相信我可以正确访问json对象,但是我不确定该错误,我需要将其作为字符串以使我的情感功能正常工作,并且我会遇到类型错误:
sentimentRating = sentimentAnalysis(x['text'])
TypeError: tuple indices must be integers or slices, not str
Here, 这里,
for x in tweet.items():
sentimentRating = sentimentAnalysis(x['text'])
x
is a tuple of your dictionary's (key,value)
so you have to pass index. x
是字典的(key,value)
的元组,因此您必须传递索引。
if you simply want the data of 'text'
key. 如果您只是想要
'text'
键的数据。 you can write tweet['text']
你可以写
tweet['text']
您的问题是x
是元组,因此您需要使用x[1]
类的数字索引,而不是字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.