python - 如何使用 TwythonStreamer 从 Twitter API 获取全文字段值
问题描述
尝试通过以下代码获取完整的推文。我了解您想将参数 tweet_mode 设置为值“扩展”,但由于我不是这里的标准查询,我不知道它适合哪里。对于文本字段,我总是会被“...”截断部分文本,然后是 URL。使用此配置,您将如何获取完整的推文:
from twython import Twython, TwythonStreamer
import json
import pandas as pd
import csv
def process_tweet(tweet):
d = {}
d['hashtags'] = [hashtag['text'] for hashtag in tweet['entities']['hashtags']]
d['text'] = tweet['text']
d['user'] = tweet['user']['screen_name']
d['user_loc'] = tweet['user']['location']
return d
# Create a class that inherits TwythonStreamer
class MyStreamer(TwythonStreamer):
# Received data
def on_success(self, data):
# Only collect tweets in English
if data['lang'] == 'en':
tweet_data = process_tweet(data)
self.save_to_csv(tweet_data)
# Problem with the API
def on_error(self, status_code, data):
print(status_code, data)
self.disconnect()
# Save each tweet to csv file
def save_to_csv(self, tweet):
with open(r'tweets_about_california.csv', 'a') as file:
writer = csv.writer(file)
writer.writerow(list(tweet.values()))
# Instantiate from our streaming class
stream = MyStreamer(creds['CONSUMER_KEY'], creds['CONSUMER_SECRET'],
creds['ACCESS_TOKEN'], creds['ACCESS_SECRET'])
# Start the stream
stream.statuses.filter(track='california', tweet_mode='extended')
解决方案
该tweet_mode=extended
参数对 v1.1 流 API 没有影响,因为所有推文都以扩展和默认 (140) 格式交付。
如果 Tweet 对象具有该值truncated: true
,则有效负载中将有一个附加元素 - extended_tweet
。这是full_text
存储值的地方。
请注意,此答案仅适用于 v1.1 Twitter API,在 v2 中,默认情况下在流 API 中返回所有 Tweet 文本(Twython 目前不支持 v2)。
推荐阅读
- java - Java 流 - 映射
> 到地图 - r - 在特定功能上使用滞后
- python - ldap3 搜索具有最少成员数的广告组
- reactjs - 被破坏对象上的打字稿接口
- python - pytesseract 不一致的结果 [Python/pytesseract]
- reactjs - 带有 REACT.js 的 ASP.NET CORE npm 运行构建代码 1
- google-apps-script - MailApp.sendEmail 方法签名异常:参数(类)不匹配
- vba - 如何将数据插入到触发存储过程的表中以将文件导出到数据库服务器端的文件夹
- python - 如何记录 Arbor 中特定细胞的峰值?
- conda - Conda 在创建虚拟环境时返回“Solving environment: done”,并且一直卡住