python - 如何在 PhpMyAdmin 中组织 CSV 的 Twitter 数据

标签 python mysql csv twitter

我正在开发一个应用程序,需要在 MySQL 数据库中存储推文集合以及推文 ID、推文日期、语言和用户名等属性。

这是我的目标图像: https://i.imgur.com/1EC3ICc.png

为此,我用 Python 创建了一个程序,以 JSON 文件形式收集 Twitter 上的 100 多条推文。然后,我使用 Microsoft Excel 将 JSON 文件转换为 CSV 文件。之后,我将 CSV 文件作为表格导入 PHPMyAdmin 中,得到以下结果:https://i.imgur.com/tLkIA0T.png (10 行 x 185 列)

上述问题是一些推文有更多数据,例如媒体,这会导致数据扩展到多个列。

如何快速清理此表,以便表中仅包含我想要的属性?我是否需要从头开始并使用我的 Python 代码工作,或者我可以从表/CSV 文件中清理吗?

最佳答案

如果推文以 JSON 格式解析,并且您只需要部分字段,我建议您使用 JSON 模块来解析所需字段,并使用 Pandas 模块将它们转换为结构化表,以便将其写入 MySQL,例如:

import json
import pandas as pd

#Open and read the text file where all the Tweets are
with open('tweets.txt') as f:
    tweets = f.readlines()
#Convert the read Tweets into JSON object
tweets_json = [json.loads(tweet) for tweet in tweets]
#Convert the list of Tweets into a structured dataframe
df = pd.DataFrame(tweets_json)
#Finally choose the attributes you need
df = df[['created_at', 'id', ...]]
#To write table into MySQL
df.to_sql(...)

关于python - 如何在 PhpMyAdmin 中组织 CSV 的 Twitter 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47314558/

相关文章:

python - 当它永远不会被实例化时,在 python 中创建一个类是否有意义?

python - 使用 Splash Scrapy POST 到 Javascript 生成的表单

php - 动态增加的可行性。数据库中的表和行

php - MYSQL函数和PHP函数,哪个更好?

php - Mysql + php 带有特殊字符,如 '(Apostrophe) and "(引号)

php - 在服务器上作为 cron 运行时强制下载生成的 CSV

python - 子类别 list

python - 在 pandas 数据框中分隔行值

java - Jackcess ExportFilter 的问题

python - Python 中 CSV 列的列表