如何使用Tweepy创建 pandas 数据框? [英] How to create a pandas dataframe using Tweepy?

查看:72
本文介绍了如何使用Tweepy创建 pandas 数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 3中,我编写了程序以提取Twitter中的帖子和喜欢的内容:

In Python 3 I made program to extract posts and likes in Twitter:

import tweepy
import pandas as pd

consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret = ''
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

此函数接收概要文件的教学分类(仅用于数据库组织)和概要文件的名称.它创建带有字典的列表,然后将其返回:

This function receives the didactic classification of profiles (only for database organization) and the name of the profile. It creates a list with dictionaries, which is then returned:

def linhadotempo(posicao, valor):
    tela = api.user_timeline(valor) 
    bolha = []
    for status in tela:
        dicionario = {"nome": valor, "posicionamento": posicao, "posts_links": status.text, "curtidas": status.favorite_count}
        bolha.append(dicionario)
    return bolha

Twitter个人资料的名称列表及其教学等级.然后转换为数据框:

List of names of Twitter profiles and their didactic ratings. Then transformed into a dataframe:

data = {
'nome': ['jeanwyllys_real', 'lucianagenro', 'jairbolsonaro', 'MBLivre'],
'posicionamento': ['esquerda', 'esquerda', 'direita', 'direita']
        }
perfis = pd.DataFrame(data, columns=['nome','posicionamento'])
perfis.reset_index()
    index   nome    posicionamento
0   0   jeanwyllys_real     esquerda
1   1   lucianagenro    esquerda
2   2   jairbolsonaro   direita
3   3   MBLivre     direita

我创建了一个最终列表,以将在函数中创建的列表放在一起.我在配置文件的数据框中进行迭代以激活该功能

I create a final list to put together the lists created in the function. I do an iteration in the dataframe of the profiles to activate the function

bolhas = []
for num, row in perfis.iterrows():
    bolha = linhadotempo(row['posicionamento'], row['nome'])
    bolhas.append(bolha)

我后来的意图是以此创建一个最终的数据框,但是没有成功.我的目的是在"curtidas","nome","posicionamento"和"posts_links"列中添加

My intention later was to create a final dataframe with this, but it did not work out. My intention was to have the columns "curtidas", "nome", "posicionamento" and "posts_links"

bolhas_final = pd.DataFrame(bolhas)
bolhas_final.reset_index()
index   0   1   2   3   4   5   6   7   8   ...     10  11  12  13  14  15  16  17  18  19
0   0   {'nome': 'jeanwyllys_real', 'posicionamento': ...   {'nome': 'jeanwyllys_real', 'posicionamento': ...   {'nome': 'jeanwyllys_real', 'posicionamento': ...   {'nome': 'jeanwyllys_real', 'posicionamento': ...   {'nome': 'jeanwyllys_real', 'posicionamento': ...   {'nome': 'jeanwyllys_real', 'posicionamento': ...   {'nome': 'jeanwyllys_real', 'posicionamento': ...   {'nome': 'jeanwyllys_real', 'posicionamento': ...   {'nome': 'jeanwyllys_real', 'posicionamento': ...   ...     {'nome': 'jeanwyllys_real', 'posicionamento': ...   {'nome': 'jeanwyllys_real', 'posicionamento': ...   {'nome': 'jeanwyllys_real', 'posicionamento': ...   {'nome': 'jeanwyllys_real', 'posicionamento': ...   {'nome': 'jeanwyllys_real', 'posicionamento': ...   {'nome': 'jeanwyllys_real', 'posicionamento': ...   {'nome': 'jeanwyllys_real', 'posicionamento': ...   {'nome': 'jeanwyllys_real', 'posicionamento': ...   {'nome': 'jeanwyllys_real', 'posicionamento': ...   {'nome': 'jeanwyllys_real', 'posicionamento': ...
1   1   {'nome': 'lucianagenro', 'posicionamento': 'es...   {'nome': 'lucianagenro', 'posicionamento': 'es...   {'nome': 'lucianagenro', 'posicionamento': 'es...   {'nome': 'lucianagenro', 'posicionamento': 'es...   {'nome': 'lucianagenro', 'posicionamento': 'es...   {'nome': 'lucianagenro', 'posicionamento': 'es...   {'nome': 'lucianagenro', 'posicionamento': 'es...   {'nome': 'lucianagenro', 'posicionamento': 'es...   {'nome': 'lucianagenro', 'posicionamento': 'es...   ...     {'nome': 'lucianagenro', 'posicionamento': 'es...   {'nome': 'lucianagenro', 'posicionamento': 'es...   {'nome': 'lucianagenro', 'posicionamento': 'es...   {'nome': 'lucianagenro', 'posicionamento': 'es...   {'nome': 'lucianagenro', 'posicionamento': 'es...   {'nome': 'lucianagenro', 'posicionamento': 'es...   {'nome': 'lucianagenro', 'posicionamento': 'es...   {'nome': 'lucianagenro', 'posicionamento': 'es...   {'nome': 'lucianagenro', 'posicionamento': 'es...   {'nome': 'lucianagenro', 'posicionamento': 'es...
2   2   {'nome': 'jairbolsonaro', 'posicionamento': 'd...   {'nome': 'jairbolsonaro', 'posicionamento': 'd...   {'nome': 'jairbolsonaro', 'posicionamento': 'd...   {'nome': 'jairbolsonaro', 'posicionamento': 'd...   {'nome': 'jairbolsonaro', 'posicionamento': 'd...   {'nome': 'jairbolsonaro', 'posicionamento': 'd...   {'nome': 'jairbolsonaro', 'posicionamento': 'd...   {'nome': 'jairbolsonaro', 'posicionamento': 'd...   {'nome': 'jairbolsonaro', 'posicionamento': 'd...   ...     {'nome': 'jairbolsonaro', 'posicionamento': 'd...   {'nome': 'jairbolsonaro', 'posicionamento': 'd...   {'nome': 'jairbolsonaro', 'posicionamento': 'd...   {'nome': 'jairbolsonaro', 'posicionamento': 'd...   {'nome': 'jairbolsonaro', 'posicionamento': 'd...   {'nome': 'jairbolsonaro', 'posicionamento': 'd...   {'nome': 'jairbolsonaro', 'posicionamento': 'd...   {'nome': 'jairbolsonaro', 'posicionamento': 'd...   {'nome': 'jairbolsonaro', 'posicionamento': 'd...   {'nome': 'jairbolsonaro', 'posicionamento': 'd...
3   3   {'nome': 'MBLivre', 'posicionamento': 'direita...   {'nome': 'MBLivre', 'posicionamento': 'direita...   {'nome': 'MBLivre', 'posicionamento': 'direita...   {'nome': 'MBLivre', 'posicionamento': 'direita...   {'nome': 'MBLivre', 'posicionamento': 'direita...   {'nome': 'MBLivre', 'posicionamento': 'direita...   {'nome': 'MBLivre', 'posicionamento': 'direita...   {'nome': 'MBLivre', 'posicionamento': 'direita...   {'nome': 'MBLivre', 'posicionamento': 'direita...   ...     {'nome': 'MBLivre', 'posicionamento': 'direita...   {'nome': 'MBLivre', 'posicionamento': 'direita...   {'nome': 'MBLivre', 'posicionamento': 'direita...   {'nome': 'MBLivre', 'posicionamento': 'direita...   {'nome': 'MBLivre', 'posicionamento': 'direita...   {'nome': 'MBLivre', 'posicionamento': 'direita...   {'nome': 'MBLivre', 'posicionamento': 'direita...   {'nome': 'MBLivre', 'posicionamento': 'direita...   {'nome': 'MBLivre', 'posicionamento': 'direita...   {'nome': 'MBLivre', 'posicionamento': 'direita...

通过显示"bolhas"的内容,我相信错误是append在列表中创建了多个列表:

By showing the content of "bolhas" I believe the error was that append created several lists within the list:

[[{'curtidas': 122,
   'nome': 'jeanwyllys_real',
   'posicionamento': 'esquerda',
   'posts_links': 'A expressão "ideologia de gênero" é uma farsa criada para combater a promoção da igualdade e perpetrar a violência… https:///lWdLANLzc5'},
  {'curtidas': 316,
   'nome': 'jeanwyllys_real',
   'posicionamento': 'esquerda',
   'posts_links': 'O termo fantasioso "ideologia de gênero" foi criado por aqueles que falam em "ditadura gay". Quando o ministro ileg… https:///zv2aY31X9p'},
...
 [{'curtidas': 378,
   'nome': 'lucianagenro',
   'posicionamento': 'esquerda',
   'posts_links': 'Que coisa mais ridícula o ministro da Educação falando em rede nacional que a nova base curricular "está sendo entr… https:///h6l95GhdWT'},
...
{'curtidas': 500,
   'nome': 'MBLivre',
   'posicionamento': 'direita',
   'posts_links': 'URGENTE: Lula pede 1 milhão de reais em indenização moral a Dallagnol e Justiça nega https://d9vVwRH2IS via @'}]]

是否存在将创建的列表合并为一个的正确方法?创建数据框时,我想保留这种结构.

Is there a correct way to merge the created lists into one? I would like to keep this structure when creating a dataframe.

推荐答案

导入我们将要使用的必需库:

Importing the required libraries that we are going to use:

import pandas as pd
import numpy as np
import tweepy
import json

提供我们的密钥以连接到Twitter API:

Providing our keys to connect to Twitter API:

consumer_key = '....'
consumer_secret = '....'
access_token = '....'
access_secret = '....'

下一步是创建OAuthHandler实例...

The next step is creating an OAuthHandler instance...

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)

...然后访问Twitter API.

...and then gain access to the Twitter API.

auth.set_access_token(access_token, access_secret)

最后,我们创建一个API对象,将使用它来获取推文:

Finally we create an API object that we are going to use it to fetch the tweets:

api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)

从巴塞罗那足球俱乐部的Twitter帐户中获取最后20条推文:

Fetching the last 20 tweets from FC Barcelona twitter account:

last_20_tweets_of_FC_Barcelona = api.user_timeline('FCBarcelona')

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

Then in this code block we isolate the json part of each tweepy status object that we have downloaded and we add them all into a list....

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

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

...and then we write this list into a txt file:

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

现在,我们将从tweet_json.txt文件创建一个DataFrame:

Now we are going to create a DataFrame from the tweet_json.txt file:

my_demo_list = []
with open('tweet_json_Barca.txt', encoding='utf-8') as json_file:  
    all_data = json.load(json_file)
    for each_dictionary in all_data:
        tweet_id = each_dictionary['id']
        text = each_dictionary['text']
        favorite_count = each_dictionary['favorite_count']
        retweet_count = each_dictionary['retweet_count']
        created_at = each_dictionary['created_at']
        my_demo_list.append({'tweet_id': str(tweet_id),
                             'text': str(text),
                             'favorite_count': int(favorite_count),
                             'retweet_count': int(retweet_count),
                             'created_at': created_at,
                            })
        #print(my_demo_list)
        tweet_json = pd.DataFrame(my_demo_list, columns = 
                                  ['tweet_id', 'text', 
                                   'favorite_count', 'retweet_count', 
                                   'created_at'])

这篇关于如何使用Tweepy创建 pandas 数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆