首页 > 解决方案 > 如何使用 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')

标签: pythontwittertwython

解决方案


tweet_mode=extended参数对 v1.1 流 API 没有影响,因为所有推文都以扩展和默认 (140) 格式交付。

如果 Tweet 对象具有该值truncated: true,则有效负载中将有一个附加元素 - extended_tweet。这是full_text存储值的地方。

请注意,此答案仅适用于 v1.1 Twitter API,在 v2 中,默认情况下在流 API 中返回所有 Tweet 文本(Twython 目前不支持 v2)。


推荐阅读