johnobc johnobc -4 years ago 220
JSON Question

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.

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 = '' + 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

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

l = StdOutListener()
stream = Stream(auth, l)
keywords = ['iknow']

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:

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

Answer Source


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.

if you simply want the data of 'text' key. you can write tweet['text']

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download