首页 > 解决方案 > Twitter Stream 的最有效方式是什么?

问题描述

我和我的搭档从年初开始学习 Python。我正处于 a) 我和我的搭档几乎完成了我们的代码,但是 b) 正在拉扯我们的头发试图让它工作。

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

而且我不知道如何更有效地拉推文。该代码有效,但它会在超时之前将大约 7-12 行信息写入 CSV。

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

我尝试将位置参数扩展为 stream.filter(locations=[-180,-90,180,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])

标签: pythontwittertweepygeocode

解决方案


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

您提供 a location,它会搜索这样的位置,但找不到location。所以它写入loc None.
因此loc.latitude将不起作用,因为locis None

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


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

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


推荐阅读