如何从Twitter Search API创建pandas数据框?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何从Twitter Search API创建pandas数据框?相关的知识,希望对你有一定的参考价值。

我正在使用Twitter Search API,它返回字典字典。我的目标是从响应字典中的键列表创建数据帧。

这里的API响应示例:Example Response

我在状态字典中有一个键列表

keys = ["created_at", "text", "in_reply_to_screen_name", "source"]

我想循环遍历状态字典中返回的每个键值,并将它们放在一个数据框中,并将键作为列。

目前有代码单独循环单个键并分配给列表然后追加到数据帧但是想要一次多做一个键的方法。目前的代码如下:

#w is the word to be queired
w = 'keyword'
#count of tweets to return
count = 1000

#API call
query = twitter.search.tweets(q= w, count = count)

def data_l2 (q, k1, k2):

    data = []

    for results in q[k1]:
        data.append(results[k2])

    return(data)

screen_names = data_l3(query, "statuses", "user", "screen_name")

data = {'screen_names':screen_names,
       'tweets':tweets}
frame=pd.DataFrame(data)
frame
答案

当我使用Twitter API时,我将分享一个我提出的更通用的解决方案。假设您要在名为my_ids的列表中获取要提取的推文ID:

# Fetch tweets from the twitter API using the following loop:
list_of_tweets = []
# Tweets that can't be found are saved in the list below:
cant_find_tweets_for_those_ids = []
for each_id in my_ids:   
    try:
        list_of_tweets.append(api.get_status(each_id))
    except Exception as e:
        cant_find_tweets_for_those_ids.append(each_id)

然后在这个代码块中我们隔离了我们下载的每个tweepy状态对象的json部分,并将它们全部添加到列表中....

my_list_of_dicts = []
for each_json_tweet in list_of_tweets:
    my_list_of_dicts.append(each_json_tweet._json)

...我们将此列表写入txt文件:

with open('tweet_json.txt', 'w') as file:
        file.write(json.dumps(my_list_of_dicts, indent=4))

现在我们将从tweet_json.txt文件创建一个DataFrame(我添加了一些与我正在使用的用例相关的键,但您可以添加特定的键):

my_demo_list = []
with open('tweet_json.txt', encoding='utf-8') as json_file:  
    all_data = json.load(json_file)
    for each_dictionary in all_data:
        tweet_id = each_dictionary['id']
        whole_tweet = each_dictionary['text']
        only_url = whole_tweet[whole_tweet.find('https'):]
        favorite_count = each_dictionary['favorite_count']
        retweet_count = each_dictionary['retweet_count']
        created_at = each_dictionary['created_at']
        whole_source = each_dictionary['source']
        only_device = whole_source[whole_source.find('rel="nofollow">') + 15:-4]
        source = only_device
        retweeted_status = each_dictionary['retweeted_status'] = each_dictionary.get('retweeted_status', 'Original tweet')
        if retweeted_status == 'Original tweet':
            url = only_url
        else:
            retweeted_status = 'This is a retweet'
            url = 'This is a retweet'

        my_demo_list.append({'tweet_id': str(tweet_id),
                             'favorite_count': int(favorite_count),
                             'retweet_count': int(retweet_count),
                             'url': url,
                             'created_at': created_at,
                             'source': source,
                             'retweeted_status': retweeted_status,
                            })
        tweet_json = pd.DataFrame(my_demo_list, columns = ['tweet_id', 'favorite_count', 
                                                       'retweet_count', 'created_at',
                                                       'source', 'retweeted_status', 'url'])

以上是关于如何从Twitter Search API创建pandas数据框?的主要内容,如果未能解决你的问题,请参考以下文章

如何从 developer.twitter.com 运行示例

如何使用Twitter API获取某些国家/地区的所有推文?

Twitter 搜索标签示例 API v1.1

如何在搜索 api 中排除转发和回复?

API爬虫--Twitter实战

twitteR R API getUser,用户名仅为数字