【问题标题】:Python Geo Scrape Using TweepyPython Geo Scrape 使用 Tweepy
【发布时间】:2020-01-22 04:07:17
【问题描述】:

我正在使用 Twitter 的 API 和 tweepy,希望从推文中抓取可用的地理位置坐标。我的最终目标是仅将每条推文的坐标存储在表格中。

我的问题是,当定位推文时,我遇到了一个错误,其中提供了比坐标更多的信息:

到目前为止我的代码如下:


import pandas as pd
import json
import tweepy
import csv

class MyStreamListener(tweepy.StreamListener):

    def on_status(self, status):

        if status.retweeted:
            return

        if True:

            coords = status.coordinates
            geo = status.geo

        if geo is not None:
            geo = json.dumps(geo)

        if coords is not None:
            coords = json.dumps(coords)    

            print(coords, geo)
            with open('coordinates_data.csv', 'a') as f:
                writer = csv.writer(f)
                writer.writerow([coords,geo])


    def on_error(self, status_code):
        if status_code == 420:
            #returning False in on_error disconnects the stream
            return False

LOCATIONS = [-124.7771694, 24.520833, -66.947028, 49.384472,        # Contiguous US
                 -164.639405, 58.806859, -144.152365, 71.76871,         # Alaska
                 -160.161542, 18.776344, -154.641396, 22.878623]        # Hawaii

auth = tweepy.OAuthHandler('access auths', 'access auths')
auth.set_access_token('token','token')

api = tweepy.API(auth)
user = api.me()

myStreamListener = MyStreamListener()
myStream = tweepy.Stream(auth = api.auth, listener=myStreamListener)  
myStream.filter(locations=LOCATIONS)

我确定这个问题与我缺乏对“json”的理解有关,或者我需要使用数据字典。

我将不胜感激!

【问题讨论】:

  • 嗨,欢迎来到 SO!这看起来像家庭作业!如果需要,请先查看asking about homeworkedit 您的问题。

标签: python json api dictionary tweepy


【解决方案1】:

澄清一下,Tweepy 是一个与 Twitter 的 API 接口的第三方库。

这就是 Twitter 代表 coordinates objects 的方式。 Tweepy 将 Status/Tweet object 数据的 coordinates 属性解析为它所在的字典。您可以简单地访问 coordinates 字段作为该字典的键,以获取包含经度和纬度值的列表。

您还缺少引号',您在其中初始化auth,但我认为这是您在替换此问题的凭据时的拼写错误。

【讨论】:

    猜你喜欢
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 2012-03-08
    • 2018-06-29
    • 1970-01-01
    • 2018-05-30
    相关资源
    最近更新 更多