You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Tweepy的search_recent_tweets筛选特定国家的推文?

解决Tweepy search_recent_tweets筛选特定国家推文的问题

核心错误分析

你之前的尝试存在几个关键用法混淆:

  • place_country是搜索查询的运算符,要求传入两位ISO国家代码(如DE代表德国),而非国家名称(如Germany)
  • place.fields是API的扩展参数,用于指定要返回的地点相关字段(如country、country_code),不是筛选条件,不能写在查询语句里
  • place_fields参数的取值只能是官方指定的字段列表,不能传入国家名称或代码

修正后的完整代码

import tweepy
import pycountry as pyc
import json

# 配置Bearer Token
BEARER_TOKEN='XXXXXXXXX'

# 初始化客户端
client = tweepy.Client(bearer_token=BEARER_TOKEN)

# 获取用户输入
countryQuery = input("Find recent tweets about travel in a certain country (input country name): ")
keyword = 'women safe'

# 获取两位ISO国家代码
try:
    country_code = pyc.countries.search_fuzzy(countryQuery)[0].alpha_2
except LookupError:
    print("无法识别该国家名称,请重新输入")
    exit()

# 构建正确的查询语句:关键词 + 国家代码筛选 + 排除转推
query = f"{keyword} place_country:{country_code} -is:retweet"

# 调用API,同时指定需要返回的推文字段和地点扩展字段
posts = client.search_recent_tweets(
    query=query,
    max_results=100,
    tweet_fields=['id', 'text', 'entities', 'author_id', 'geo'],
    expansions="geo.place_id",
    place_fields=["country", "country_code", "full_name"]
)

# 处理返回结果
if posts.data:
    # 导出推文到JSON
    with open('twitter.json', 'w') as fp:
        for tweet in posts.data:
            # 如果推文有地点关联,补充地点信息
            tweet_data = tweet.data
            if tweet.geo and tweet.geo.get('place_id'):
                place = next(p for p in posts.includes.get('places', []) if p.id == tweet.geo['place_id'])
                tweet_data['place_info'] = place.data
            json.dump(tweet_data, fp)
            fp.write('\n')
            print(f"* {tweet.text}")
else:
    print("未找到符合条件的推文")

关键修改说明

  1. 查询语句修正:用place_country:{country_code}替代原有的国家名称,确保符合Twitter搜索运算符的要求
  2. 扩展参数正确使用:
    • expansions="geo.place_id":告诉API需要关联返回推文对应的地点信息
    • place_fields:指定要返回的地点字段(可选值参考官方文档:contained_within, country, country_code, full_name, geo, id, name, place_type)
  3. 异常处理:增加国家名称识别的异常捕获,避免输入无效名称导致崩溃
  4. 结果处理优化:如果推文有地点信息,将地点详情补充到导出的JSON中

无结果的可能原因

如果仍然返回None,可能是以下情况:

  • 该国家近期没有包含指定关键词的非转推推文
  • 大部分推文未标记地理位置(Twitter用户需主动开启地点标记才会被筛选到)

内容的提问来源于stack exchange,提问作者user21102907

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 20:30:41