Twitter流媒体的最有效方式



我和我的伙伴从年初开始学习Python。我现在的处境是:a(我和我的合作伙伴几乎完成了我们的代码,但b(正在竭尽全力让它发挥作用。

任务:根据某个主题提取250条推文,对推文的地理位置进行编码,根据情绪进行分析,然后在网络地图上显示。除了250条推特的要求外,我们几乎已经完成了所有这些。

我不知道如何更有效地提取推文。代码是有效的,但在超时之前,它会将大约七到十二行的信息写入CSV。

我尝试设置跟踪参数,但收到此错误:TypeError: 'NoneType' object is not subscriptable'

我尝试将locations参数扩展到stream.filter(locations=[-180,-90180,90](,但收到了相同的问题:TypeError: 'NoneType' object has no attribute 'latitude'

我真的不知道我错过了什么,我想知道是否有人有任何想法。

下面的代码:

from geopy import geocoders
from geopy.exc import GeocoderTimedOut
import tweepy
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
from textblob import TextBlob
import json
import csv
def geo(location):
g = geocoders.Nominatim(user_agent='USER')
if location is not None:
loc = g.geocode(location, timeout=None)
if loc.latitude and loc.longitude is not None:
return loc.latitude, loc.longitude
def WriteCSV(user, text, sentiment, lat, long):
f = open('D:/PATHWAY/TO/tweets.csv', 'a', encoding="utf-8")
write = csv.writer(f)
write.writerow([user, text, sentiment, lat, long])
f.close()
CK = ''
CS = ''
AK = ''
AS = ''
auth = tweepy.OAuthHandler(CK, CS)
auth.set_access_token(AK, AS)
#By setting these values to true, our code will automatically wait as it hits its limits
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
#Now I'm going to set up a stream listener
#https://stackoverflow.com/questions/20863486/tweepy-streaming-stop-collecting-tweets-at-x-amount
#https://wafawaheedas.gitbooks.io/twitter-sentiment-analysis-visualization-tutorial/sentiment-analysis-using-textblob.html        
class StdOutListener(tweepy.StreamListener):
def __init__(self, api=None):
super(StdOutListener, self).__init__()
self.num_tweets = 0
def on_data(self, data):
Data = json.loads(data)
Author = Data['user']['screen_name']
Text = Data['text']
Tweet = TextBlob(Data["text"])
Sentiment = Tweet.sentiment.polarity
x,y = geo(Data['place']['full_name'])
if "coronavirus" in Text:
WriteCSV(Author, Text, Sentiment, x,y)
self.num_tweets += 1
if self.num_tweets < 50:
return True
else:
return False
stream = tweepy.Stream(auth=api.auth, listener=StdOutListener())
stream.filter(locations=[-122.441, 47.255, -122.329, 47.603])

Twitter和Geolocation API返回所有类型的数据。某些字段可能丢失。

TypeError: 'NoneType' object has no attribute 'latitude'

这个错误来自这里:

loc = g.geocode(location, timeout=None)
if loc.latitude and loc.longitude is not None:
return loc.latitude, loc.longitude

您提供了一个location,它会搜索该位置,但找不到该location。因此它写入locNone
因此loc.latitude无法工作,因为locNone

在访问loc的任何属性之前,应该先检查它。


x,y = geo(Data['place']['full_name'])

我知道你在按位置过滤推文,因此你的推特状态对象应该有Data['place']['full_name']。但情况并非总是如此在访问值之前,您应该检查该键是否确实存在
这通常适用,并且应该应用于整个代码。编写健壮的代码。如果您实现一些try catch并打印出对象以查看它们是如何构建的,那么调试错误会更容易一些。也许可以在捕获中设置一个断点,并进行一些实时检查。

最新更新