【问题标题】:Most efficient way to Twitter Stream?Twitter Stream 的最有效方式是什么?
【发布时间】:2020-06-14 13:55:47
【问题描述】:

我和我的搭档从年初开始学习 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])

【问题讨论】:

  • 第一次导入后的缩进是错误的吗?进口不应缩进

标签: python twitter tweepy geocode


【解决方案1】:

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'])

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    • 2016-08-24
    • 2020-01-25
    • 1970-01-01
    相关资源
    最近更新 更多