如何纠正KeyError或继续它

时间:2016-12-24 04:26:58

标签: python

我正在使用此代码来关注Twitter帐户,如果特定的单词是Twitter,则打印文本和推文ID然后删除推文。下面的代码就像它找到单词' hi'当发推文时,打印它和id,并删除推文。问题是,在删除推文后,我立即收到错误 - KeyError 'text'。并且脚本停止了。我是python的新手,对字典,异常或KeyError不太了解。如何设置异常以忽略此错误并继续或创建字典和其他代码,以便不会发生错误?

import time
from twython import TwythonStreamer
from twython import Twython



# Twitter application authentication
APP_KEY = ''
APP_SECRET = ''
OAUTH_TOKEN = ''
OAUTH_TOKEN_SECRET = ''


twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)


# Setup callbacks from Twython Streamer
class TweetStreamer(TwythonStreamer):
        def on_success (self, data):
            if (data['text']) == ('hi'):
                print (data['text'])
                print (data['id'])
                time.sleep(2)
                twitter.destroy_status(id=data['id'])
                print ('Tweet was deleted')


        def on_error(self, status_code, data):
                print (status_code)


# Create streamer
try:
        stream = TweetStreamer(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
        stream.statuses.filter(follow = '')

except KeyboardInterrupt:
        print ('Process manually stopped')

完整错误:

Traceback (most recent call last):
  File "C:\Users\MainUser\Desktop\Python Scripts\twitterstreamuser.py", line 35, in <module>
    stream.statuses.filter(follow = '')
  File "C:\Users\MainUser\AppData\Local\Programs\Python\Python35-32\lib\site-packages\twython\streaming\types.py", line 66, in filter
    self.streamer._request(url, 'POST', params=params)
  File "C:\Users\MainUser\AppData\Local\Programs\Python\Python35-32\lib\site-packages\twython\streaming\api.py", line 154, in _request
    if self.on_success(data):  # pragma: no cover
  File "C:\Users\MainUser\Desktop\Python Scripts\twitterstreamuser.py", line 20, in on_success
    if (data['text']) == ('hi'):
KeyError: 'text'

1 个答案:

答案 0 :(得分:0)

您尝试从"text"

获取data
data["text"]

data没有密钥"text"

您可以检查data是否有密钥"text"

if 'text' in data:
   if data['text'] == 'hi':
       print(data['text'])

或更短

if 'text' in data and data['text'] == 'hi':
    print(data['text'])

或使用data.get("text")(或data.get("text", "default text"))获取"text""default text"(或None

msg = data.get("text") # it gives data["text"] or `None`
if msg == 'hi':
   print(msg)