首页 > 解决方案 > 是否有可能知道特定推文的来源国?

问题描述

我正在解决一个问题,该问题需要我知道推文的来源国。我不需要更小的粒度。只是国家会这样做。我已经有了这些推文。是否可以从 twitter API 获取此信息?

Twitter API 提到:

Places:当存在时,表示推文与 Place 相关联(但不一定源自)。

坐标:表示用户或客户端应用程序报告的此推文的地理位置。内部坐标数组格式为 geoJSON(先是经度,后是纬度)。

一些搜索显示,Places 可能不是执行此操作的最佳方式。我应该改用坐标吗?它们准确吗?使用它有什么“陷阱”吗?

标签: twitter

解决方案


我使用位置参数从边界框获取推文。这将返回普通推文和地理标记推文。

请注意,如果坐标字段已填充或坐标为空但地点已填充,则流将返回推文。如果坐标字段不为空,则它表示地球表面上推文起源的确切位置(地理标记推文)。如果坐标字段为空,但显示了地点字段,它将显示代表用户在该普通推文中标记的地点的边界框/多边形的坐标(范围从博物馆到城市/国家)。Twitter 还能够从 IP 地址中检索一些位置信息(尽管粒度较低,例如城市级别)。详细信息可以在https://developer.twitter.com/en/docs/tweets/filter-realtime/guides/basic-stream-parameters中找到。

l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
stream.filter(locations = [144.9385,-37.8246,144.9761,-37.7955])

编辑:当您使用 Streaming API 在 .txt 文件中提取一组推文时,您可以使用以下代码。我使用了一个名为 Tweet Parser 的 Python 包。

import pandas as pd
from tweet_parser.tweet import Tweet
from tweet_parser.tweet_parser_errors import NotATweetError
import fileinput
import json

#remove all blank lines
with open('test.txt') as infile, open('test.json', 'w') as outfile:
    for line in infile:
        if not line.strip(): continue  # skip the empty line
        outfile.write(line)  # non-empty line. Write it to output

df  = pd.DataFrame(columns=['DateTime','user_id','country','tweet'])
for line in fileinput.FileInput("test.json"):
    try:
        tweet_dict = json.loads(line)
        tweet = Tweet(tweet_dict)
    except (json.JSONDecodeError,NotATweetError):
        pass
    df= df.append({'DateTime':tweet.created_at_datetime,'user_id':tweet.user_id,'country':tweet_dict['place']['country'],'tweet':tweet.text},ignore_index=True)

在此处输入图像描述


推荐阅读