【发布时间】: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