我正在尝试将推文从我的流监听器推送到 mysql 数据库。当我在推文中包含推文位置时,代码可以工作,但如果不包含推文位置,则代码会失败。
我如何完全覆盖它,以便它写入数据库可用的任何推文数据?
def on_data(self, data):
all_data = json.loads(data)
tweets = (all_data["text"])
tweet = re.sub(r"http\S+", "", tweets) #removes URL from tweet text and outputs tweet
created_at_time = all_data["created_at"]
created_at = re.sub(r"\+\S+\s", "", created_at_time) #removes +0000 from tweet text and outputs created_at
#image = all_data["extended_entities"]["media"][0]["media_url_https"]
#lng, lat = all_data["coordinates"]["coordinates"]
tweet_location = (all_data["place"]["full_name"])
c.execute("INSERT INTO location (tweet, created_at, tweet_location) VALUES (%s,%s,%s)",
(tweet, created_at, tweet_location))
conn.commit()
print((tweet, created_at))
return True
def on_error(self, status):
print (status)
每当我在没有 tweet_location 的情况下发推文时,我都会收到以下错误:
发生异常:类型错误 “NoneType”对象不可订阅
最佳答案
我能够通过删除以下内容来解决该问题:
tweet_location = (all_data["place"]["full_name"])
然后将以下键添加到列表中:
location = (all_data["place"])
tweet_location = (all_data["place"])
然后添加这个 if/else:
if location is not None:
tweet_location = (all_data["place"]["full_name"])
else:
pass
关于php - 当推文中不包含坐标或图像时,Tweepy 流监听器的代码给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56153353/