最有效的Twitter流方式?

问题描述 投票:0回答:1

我和我的伴侣从年初开始学习Python。我正处于这样的时刻:a)我的伙伴和我的代码都快写完了,但是b)正在努力使它发挥作用。

[分配:根据特定主题拉出250条推文,对推文进行地理编码,根据情感进行分析,然后将其显示在网络地图上。除250条推文要求外,我们几乎完成了所有这些任务。

而且我不知道如何更有效地发布推文。该代码有效,但是在超时之前,它会在CSV上写入大约七十二行信息。

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

我尝试将locations参数扩展为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个回答
0
投票

Twitter and 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。因此它写入loc None。因此,loc.latitude将不起作用,因为locNone

访问任何属性前,请先检查loc


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

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

© www.soinside.com 2019 - 2024. All rights reserved.