我使用 locations 参数从边界框获取推文。这将返回普通推文和带有地理标记的推文。
请注意,如果坐标字段已填充或坐标为空但地点已填充,则流将返回推文。如果坐标字段不为空,它表示地球表面上推文起源的确切位置(地理标记推文)。如果坐标字段为空,但显示了地点字段,它将显示代表用户在该普通推文中标记的地点的边界框/多边形的坐标(范围从博物馆到城市/国家)。 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)