如何使用 Tweepy 创建 pandas 数据框?

2023-11-21

在 Python 3 中,我编写了一个程序来提取 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)

该函数接收配置文件的教学分类(仅适用于数据库组织)和配置文件的名称。它创建一个包含字典的列表,然后返回该列表:

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 个人资料名称列表及其教学评级。然后转化为数据框:

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

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

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

我后来的意图是用它创建一个最终的数据框,但没有成功。我的意图是拥有“curtidas”、“nome”、“posicionamento”和“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”的内容,我相信错误是追加在列表中创建了多个列表:

[[{'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 @'}]]

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


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

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

提供连接 Twitter API 的密钥:

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

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

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)

...然后获取 Twitter API 的访问权限。

auth.set_access_token(access_token, access_secret)

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

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

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

last_20_tweets_of_FC_Barcelona = api.user_timeline('FCBarcelona')

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

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 文件:

with open('tweet_json_Barca.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_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'])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Tweepy 创建 pandas 数据框? 的相关文章

随机推荐

  • Global.asax 中的事件未触发

    在我的 ASP Net 应用程序中 我无法在我的计算机上触发 Global asax 中的事件 例如 Session Start 将不会触发 同样的 Global asax 在我办公室的其他开发机器上运行良好 我努力了 ASP Net 开发
  • 我可以对指向 void 指针的指针使用指针算术吗?

    我知道你不能对 void 指针使用指针算术 但是理论上你可以对指向 void 指针的指针进行指针算术吗 因为sizeof void 会产生一个指针在您的系统上占用多少字节的答案 不允许进行指针运算void 因为void是一个不完整的对象类型
  • 以编程方式初始化 ViewController

    我正在尝试初始化一个UIViewController在我的 Swift 应用程序中 但我面临一个问题 我找不到任何明确的答案 我想从 FlowCoordinator 调用它来初始化控制器 但由于需要 init coder NSCoder 函
  • C++ Switch 无法使用用作 case 的外部定义变量进行编译

    我正在使用 MinGW GNU 编译器编写 C 当我尝试使用外部定义的整数变量作为 switch 语句中的 case 时 就会出现问题 我收到以下编译器错误 case 标签不会减少为整数常量 因为我已将整数变量定义为 extern 我相信它
  • Bootstrap Modals 和 Youtube:自动播放并在关闭时停止

    我需要能够在 Twitter Bootstrap 模式打开时自动播放 YouTube 视频 然后在关闭时停止该视频 我知道这个问题之前已经被问过 但我能找到的答案会导致包含许多视频的页面出现大量 javascript 代码 我正在努力减少膨
  • 如何在 IVY 中没有提供的情况下复制运行时库

    我以为我不需要问这个 但我没有任何进展 这个问题的解答 ivy如何将maven范围映射到ivy配置实际上解决了问题 但在理论部分 我有这样的配置
  • 如何为类的私有和公共成员分配内存

    在类中 私有成员是与公共成员分配在单独的内存中 还是所有成员都按照其定义的顺序分配 例如 class A private int a1 int a2 3 public int z int a3 2 int a4 5 private int
  • System.UnauthorizedAccessException:对路径“...”的访问被拒绝

    我使用 net 使用单击一次安装完成了 C wpf 安装 一切正常 然后我有以下代码 它是已安装程序的一部分 String destinationPath System Windows Forms Application StartupPa
  • 检测输入类型文本的编程更改[重复]

    这个问题在这里已经有答案了 当脚本更改输入类型文本的值时 有没有办法获得通知 I have
  • R:从字符串中删除最后三个点

    我有一个文本数据文件 我可能会用它来读取readLines 每个字符串的初始部分包含很多乱码 后面是我需要的数据 乱码和数据通常由三个点分隔 我想在最后三个点之后分割字符串 或者用某种标记替换最后三个点 告诉 R 将这三个点左侧的所有内容视
  • 将 scipy.stats.gaussian_kde 与二维数据一起使用

    我正在尝试使用the scipy stats gaussian kde class把一些离散的经纬度信息采集到的数据进行平滑处理 所以最后看起来有点像等高线图 密度高的就是峰 密度低的就是谷 我很难将二维数据集放入gaussian kde班
  • CakePHP 控制器别名

    我知道还有一些关于这个主题的其他主题 但似乎没有一个适合我的需要 我拥有的 example com log 日志控制器 php I have LogsController代替LogController 复数 因为 CakePHP 希望你有复
  • 应用程序服务器和 servlet 容器之间的区别?

    我试图理解成熟的应用程序服务器 例如 Weblogic JBoss 等 和 servlet 容器 Tomcat Jetty 等 之间的区别 它们有何不同以及何时使用哪个 Thanks servlet 容器仅支持 servlet API 包括
  • 整页 Malloc

    我试图通过一次使用整个页面来优化程序的内存分配 我正在获取这样的页面大小 sysconf SC PAGESIZE 然后计算适合页面的元素总数 如下所示 elements pageSize sizeof Node 我在想 当我真正去 mall
  • C# - PowerStatus 更改时引发事件

    我创建了一个需要处于安全状态的应用程序 因此我想在后台跟踪计算机的电源状态 如果电池电量 如果有 较低或严重 我不会允许用户继续使用该应用程序并正确退出 首先 我很惊讶不存在这样的事件来检测变化 您始终需要手动检查电源状态 所以 我围绕它创
  • 如何使用库调用计算 C# 中的阶乘?

    我需要计算 100 左右的数字的阶乘 为了确定一系列硬币翻转式数据是否是随机的 根据这是关于贝叶斯概率的维基百科条目 正如您所看到的 必要的公式涉及 3 个阶乘计算 但有趣的是 其中两个阶乘计算是在第三个阶乘计算的过程中计算的 I saw
  • JAXB - 从 url 解组

    我正在尝试显示此网站的游戏标题和 ID http thegamesdb net api GetGame php id 2 当我从这个网址解组时 http www w3schools com xml note xml一切都很好 但这里只是一个
  • Browserify 无法使用 babelify 转换创建包(类型错误:路径必须是字符串。)

    我编写了一个 gulp 任务 使用 watchify 和 babelify 作为转换将我的 jsx 和 js 脚本编译成一个包 由于某种原因 我的 gulp 脚本似乎在转换时被阻塞 我不知道为什么 gulp task browserify
  • C++20 constexpr 容器如何工作?

    As constexpr std string and constexpr std vector已被 C 20 接受 将如何使用它们 链接的论文细节非常简短 我们是否需要指定特殊的constexpr分配器 使编译时字符串 向量与它们的正常等
  • 如何使用 Tweepy 创建 pandas 数据框?

    在 Python 3 中 我编写了一个程序来提取 Twitter 中的帖子和点赞 import tweepy import pandas as pd consumer key consumer secret access token acc