1

I am getting tweets from twitter about verizon and everthing is good according to the code below, but I do not understand why I am getting error KeyError "text"?

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

# consumer key, consumer secret, access token, access secret.
ckey = "xxxxxxxxxxxxxxxxxxxx"
csecret = "xxxxxxxxxxxxxxxxxxxx"
atoken = "xxxxxxxxxxxxxxxxxxxx"
asecret = "xxxxxxxxxxxxxxxxxxxx"

class listener(StreamListener):
    def on_data(self, data):
        all_data = json.loads(data)
        tweet = all_data["text"]
        out = open('verizon_twitter_data.txt', 'a+')
        tweet=tweet.encode('utf-8')
        out.write(str(tweet)+"\n")

        print (tweet)

        out.close()
        return True

    def on_error(self, status):
        print (status)

auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
twitterStream.filter(track=['verizon', 'vzw','verizzon',    'vrizon','verizonfois',
                        'verzon','verizun','vrzon','veerizon','verrizon', 'veriizon'], languages=["en"])

I got this error after some time like an hour or more:

Traceback (most recent call last):
 File "C:/Users/amjhool2013/Desktop/untitled4/untitled4/main.py", line 32, in <module>
'verzon','verizun','vrzon','veerizon','verrizon', 'veriizon'], languages=["en"])
  File "C:\Python27\lib\site-packages\tweepy\streaming.py", line 445, in filter
    self._start(async)
  File "C:\Python27\lib\site-packages\tweepy\streaming.py", line 361, in _start
    self._run()
  File "C:\Python27\lib\site-packages\tweepy\streaming.py", line 294, in _run
    raise exception
KeyError: 'text'

1 Answer 1

0

If you just want to avoid the error on the occasional tweet that fails in the stream, you could create an exception:

try:
    tweet = all_data["text"]
    out = open('verizon_twitter_data.txt', 'a+')
    tweet = tweet.encode('utf-8')
    out.write(str(tweet)+"\n")
except KeyError:
    # do something else           
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.