Python基于Twitter API V2筛选author.description含doctor的CSV行问询
解决方案
一、Twitter API V2 直接查询过滤(推荐,无需后续本地处理)
- 你之前的参数不生效是因为误用了排除运算符
-:加-bio:doctor的作用是排除简介包含doctor的内容,和你的需求完全相反。 - Twitter API V2 搜索的正确筛选语法是直接在query字段加
bio:doctor,修改后的query参数如下:
query_params = {'query': 'vaccine bio:doctor -is:retweet -is:verified -baby -lotion -shampoo lang:en has:geo place_country:US', 'tweet.fields':'created_at,lang,text,geo,author_id,id,public_metrics,referenced_tweets', 'expansions':'geo.place_id,author_id', 'place.fields':'contained_within,country,country_code,full_name,geo,id,name,place_type', 'user.fields':'description,username,id', 'start_time':'2021-01-20T00:00:01.000Z', 'end_time':'2021-02-17T23:30:00.000Z', 'max_results':'10'}
- 按上述修改后,API返回的结果就已经是用户简介包含doctor的内容,导出的csv无需再做额外处理。
二、Pandas 本地筛选实现
如果已经拿到全量数据,不需要用iloc,直接通过列名做布尔索引筛选即可,无需打开csv文件修改,只需要在导出csv前加一行筛选逻辑即可:
你当前数据里用户简介对应的列名为author.description,修改后的main函数代码如下:
def main(): headers = create_headers(bearer_token) json_response = connect_to_endpoint(search_url, headers, query_params) json_response = expansions.flatten(json_response) df = pd.json_normalize(json_response['data']) # 筛选author.description包含doctor的行,na=False避免空值报错 # 如需不区分大小写,可添加case=False参数:str.contains('doctor', case=False, na=False) df = df[df['author.description'].str.contains('doctor', na=False)] df.to_csv("myfile.csv", encoding="utf-8-sig")
你提到的列结构可参考下图:
内容的提问来源于stack exchange,提问作者Poppy
相关产品推荐
相关产品推荐

