Python 社交媒体数据实时分析

2025年3月17日 | 阅读13分钟
Real-Time Data Analysis from Social Media Data in Python

本教程大纲

  • 本地和通用认知过程
  • 提高输出
  • 识别常见趋势
  • 深入研究最热门的趋势
  • 频率分析
  • 趋势相关活动
  • 一张可能胜过千言万语的表格
  • 对所使用语言的分析
  • 总结 - 摘要

全球和本地模式

即使我们可能不是 Twitter 爱好者,我们也必须认识到它对全球产生了重大影响。除了蕴含丰富的见解,Twitter 数据还提供对 Twitter 风暴的近实时监控。这意味着我们可以随着全球思想和情感浪潮的出现而捕捉到它们。

正如任何富饶之地一样,Twitter 的安全人员阻止我们立即访问数据以使用其应用程序编程接口 (API) 进行数据收集;必须遵循几个身份验证程序。我们已经获得了安全部门的绿卡,因为我们今天的目标是学习如何从数据中提取见解。在数据集文件夹中,我们的数据可用,Twitter 提供本地和全球趋势。让我们加载并检查在查询时在全球和美国流行的主题数据——这是对 Twitter 的 GET trends /place API 调用返回的 JSON 响应示例。

社交媒体数据集

导入适当的 Python 库并使用正确的数据集将使我们能够开始使用 Python 对社交媒体数据进行实时数据分析

. 主表(仅供参考):

屏幕名称文本关注者收藏
katyperryRT @katyperry:当然,穆勒报告已经发布,但 @lildickymessages 的“地球”今晚也将发布。你难道不能说我从未尝试过拯救吗?----------10719556910557
10719556810556
艾伦秀RT @TheEllenShow:.@lildickymessages、@justinbieber、@MileyCyrus、@katyperry、@ArianaGrande 等等,都在一个音乐视频中。我的头可能----------7747484610086
莱奥迪RT @LeoDi:受益于此次合作的 @ 合作伙伴包括 @SharkRayFund、@SolutionsProj、@GreengrantsFun----------1898889878137
RT @LeoDi:感谢 @lildickymessages 和所有为促成此事而齐心协力的艺术家们。歌曲、视频的净利润……18988898416018
halseyRT @halsey:??? 喵喵 ? #WeLikeTheEarth https://#/JJr6vmKG7U1056484469684
1056484169684
Scooter braunRT @scooterbraun:立即观看 #EARTH! #WeLikeTheEarth ----------388517914635
SpotifyRT @Spotify:这真是史诗级。@lildickymessages 邀请了 @justinbieber、@arianagrande、@halsey、@sanbenito、@Sheeran、@SnoopDogg、@Shawn Mendes----------4973477437459
TomHallRT @TomHall:? 当心!? #Cheetah @LeoDi #FridayFeeling #WeLikeTheEarth https://#/w1O1NyTbwX----------590841454
thingyRT @thingy:/rat/ 伙计们听这首歌!!! #WeLikeTheEarth https://#/trUgRG7QBH----------44597743
SB__ProjectsRT @SB__Projects:#WeLikeTheEarth 现已发布,与 @lildickymessages、@justinbieber、@ArianaGrande、@zacbrownband 以及 45+ 位您最喜爱的其他艺人合作 htt…98418730

读取数据

源代码片段

美化预期输出

我们需要易于阅读的数据!幸运的是,我们可以使用 Jason.dumps() 函数将其格式化为类似 JSON 的字符串。

源代码片段

输出

W W trends: [{'trends': [{'name': '#BeratKandili', 'url': 'http: / /twitter.com /search?q= % 43BeratKandili', 'promoted__content': None, 'query': ' % 43BeratKandili', 'tweet__volume': 46373}, {'name': '#GoodFriday', 'url': 'http: / /twitter.com /search?q= % 43GoodFriday', 'promoted__content': None, 'query': ' % 43GoodFriday', 'tweet__volume': 81891}, {'name': '#WeLikeTheEarth', 'url': 'http: / /twitter.com /search?q= % 43WeLikeTheEarth', 'promoted__content': None, 'query': ' % 43WeLikeTheEarth', 'tweet__volume': 159698}, {'name': '#195TLdenTTVeril: None, 'query': ' % E6 % B1 % A0 % E8 % A4 % 8B % E3 % 81 % AE % E4 % BA % 8B % E6 % 95 % 85', 'tweet__volume': 34381}, {'name': '????', 'url': 'http: / /twitter.com /search?q= % E3 % 83 % 97 % E3 % 83 % AA % E3 % 84 % A6 % E3 % 84 % B9', 'promoted__content': None, 'query': ' % E3 % 83 % 97 % E3 % 83 % AA % E3 % 84 % A6 % E3 % 84 % B9', 'tweet__volume': 44944}, {'name': 'Hemant Karkare', 'url': 'http: / /twitter.com /search?q= % 44Hemant+Karkare % 44', 'promoted__content': None, 'query': ' % 44Hemant+Karkare % 44', 'tweet__volume': 44067}}]

寻找相似的趋势

从精美打印的结果(前面任务的输出)中我们可以看到

  • 我们的趋势对象数组中包含趋势主题的名称、可用于在 Twitter-Search 上搜索主题的查询参数、搜索查询 URL,以及(如果可用)过去 44 小时内的消息量。趋势每五分钟更新一次。
  • 在搜索期间,#BeratKandili、#GoodFriday 和 #WeLikeTheEarth 等标签在 W W 上很受欢迎。
  • "tweet__volume" 表示在这三者中,#WeLikeTheEarth 是最常用的流行标签。
  • "Tweet__volume" 不用于结果排序。
  • 美国有几种独特的趋势。

可以快速浏览这两种趋势以识别共同模式,但让我们避免“手动”操作。我们可以遍历这两个趋势对象,将个人列表转换为集合,然后执行交集函数,使用 Python 的集合数据结构获取两个集合共有的名称。

源代码片段

输出

{'# BLACKPINKxCorden', '東京・池袋衝突事故', '# ViernesSanto', '# Karfreitag', '# AFLNorthDons', '# HardikPatel', '# NRLBulldogsSouths', 'Lyra McKee', '# DuyguAsena', '�rg�tde?il arkada?grubu', 'Shiv Sena', '# يوم__الجمعه', 'プリウス', '# TheJudasInMyLife', '# ConCalmaRemix', '# DragRace', '重体の女性と女児', '# WeLikeTheEarth', 'Derry', 'Lil Dicky', '# ShivSena', 'Derrick White', 'Priyanka Chaturvedi', '# KpuJanganCurang', '# BeratKandili', '# Hay?rl?Cumalar', '# HanumanJayanti', '# CHIvLIO', '# Jersey', '# DinahJane1', '# JunquerasACN', '브이알', 
{'# BLACKPINKxCorden', 'Seth Abramson', '# WorldofWarcraftMains', '# MakeAMovieSensual', '# AFLNorthDons', 'Kevin Durant', '# WGAMIX', '# NRLBulldogsSouths', '# GSWvsLAC', 'Lyra McKee', 'Mike Anderson', 'Oshie', '# WhatStopsYouFromGoingHome', '# FridayFeeling', '# GossipShouldBe', '# StarTrekDiscovery', 'David Fletcher', '# TimeToImpeach', 'Tomas Hertl', 'Silky', '# ConCalmaRemix', '"Earth"', '# TheLegendOfVoxMachina', '# DragRace', '# LilDicky', 'Derry', '# WeLikeTheEarth', 'Lil Dicky', '# MyInnerDemonSaid', 'WE LIKE THE EARTH', 'Derrick White', 'Yvie', '# RPDR', 'Gallant', 'Lone Wolf and Cub', '# DinahJane1', '# HustleAndSoul', '# fridaymotivation', '# MyDrunkUncleSays', '# CUZILIKEYOU', 'Shy Glizzy', 'George Conway', 'Servais', '# CriticalRoleSpoilers', '# WeirdDateStories', '# DontChangeOutNow', '# Earth', 'Kazuo Koike', '# rupaulsdragrace', 'Game 6'} 

11 common trends: {'# BLACKPINKxCorden', 'Derrick White', '# AFLNorthDons', '# NRLBulldogsSouths', 'Lyra McKee', '# ConCalmaRemix', '# WeLikeTheEarth', '# DinahJane1', '# DragRace', 'Derry', 'Lil Dicky'}

热门趋势探索

从两组趋势(每组五十个)中,我们可以从交集(最终输出)中观察到有 11 个重叠主题。一个普遍的趋势特别引人入胜:看到 Twitter 上的每个人都用 #WeLikeTheEarth 标签表达他们对地球母亲的喜爱,这令人鼓舞。当我们运行查询以收集趋势时,美国人民对仅适用于他们的事情感到愤怒,因此我们的重叠很少或多得多。

源代码片段

解释: 我们发现了一个趋势:#WeLikeTheEarth。现在让我们看看它正在向我们呐喊的故事!以该标签作为查询参数,我们可以通过 Twitter 的搜索 API 检索与之相关的消息。搜索 API 返回的“WeLikeTheEarth.json”文件是我们保存的内容。因此,让我们加载此数据集并更详细地调查此模式。

源代码片段

输出

[{'contributors': None,
  'coordinates': None,
  'created__at': 'Fri Apr 19 08:46:48 +0000 4019',
  'entities': {'hashtags': [{'indices': [30, 45], 'text': 'WeLikeTheEarth'}],
   'symbols': [],
   'urls': [{'display__url': 'youtu.be /pvuN__WvF1to',
     'expanded__url': 'https: / /youtu.be /pvuN__WvF1to',
     'indices': [46, 69],
     'url': 'https: / /t.co /L44XsoT5P1'}],
   'user__mentions': [{'id': 1409516660,
     'id__str': '1409516660',
     'indices': [3, 18],
     'name': 'LD',
     'screen__name': 'lildickymessages'}]},
  'favorite__count': 0,
  'favorited': False,
  'geo': None, 'id': 1119160405470543904,
  'id__str': '1119160405470543904', 'in__response__to__screen__name': None,
  'in__response__to__status__id': None, 'in__response__to__status__id__str': None,
  'in__response__to__user__id': None, 'in__response__to__user__id__str': None,
  'is__quote__status': False, 'lang': 'en',
  'metadata': {'iso__language__code': 'en', 'result__type': 'recent'}, 'place': None,
  'possibly__sensitive': False,
  'retweet__count': 7484,  'retweeted': False, 'retweeted__status': {'contributors': None,  'coordinates': None, 'created__at': 'Fri Apr 19 04:44:49 +0000 4019',
   'entities': {'hashtags': [{'indices': [10, 45], 'text': 'WeLikeTheEarth'}],
    'symbols': [], 'urls': [{'display__url': 'youtu.be /pvuN__WvF1to',
      'expanded__url': 'https: / /youtu.be /pvuN__WvF1to',  'indices': [46, 49],
      'url': 'https: / /t.co /L44XsoT5P1'}], 'user__mentions': []},
   'favorite__count': 13317, 'translator__type': 'none',
    'url': 'https: / /t.co /aFrPkkJKqs', 'utc__offset': None,
    'verified': True}},
  'source': '<a href="http: / /twitter.com /download /android" rel="nofollow">Twitter for Android< /a>',
  'text': 'RT @lildickymessages: ? out now #WeLikeTheEarth https: / /t.co /L44XsoT5P1',   'truncated': False,
  'user': {'contributors__enabled': False,
   'created__at': 'Fri Nov 05 44:45:49 +0000 4010',
   'default__profile': False,
   'default__profile__image': False,
   'description': "''you just got knocked the fuck out''",
   'entities': {'description': {'urls': []},
    'url': {'urls': [{'display__url': 'likeeeujdb.tumblr.com',
       'expanded__url': 'http: / /likeeeujdb.tumblr.com /',
       'indices': [0, 43]}]

深入挖掘

打印最初的两条消息项有助于我们认识到消息远不止是一条简短的文本消息,我们通常就是这样认为的。让我们通过消息对象中的数据量来保持冷静!看看我们能否通过关注一些引人入胜的主题来发现想法。

源代码片段

输出

[  "RT @lildickymessages:  \ ud83c \ udf0e out now #WeLikeTheEarth https: / /t.co /L44XsoT5P1",
 " \ ud83d \ udc9a \ ud83c \ udf0e \ ud83d \ udc9a  #WeLikeTheEarth  \ ud83d \ udc47 \ ud83c \ udffc",
 "RT @cabeyoomoon: Ta piosenka to bop,  wpada w ucho  i dochody z niej id \ u0105 na dobry cel,  warto s \ u0144ucha \ u0107 w k \ u00f3 \ u0144ko i w k \ u00f3 \ u0144ko gdziekolwiek si \ u0119 ty \ u4046",
 "#WeLikeTheEarth  \ nCzemu ja si \ u0119 pop \ u0144aka \ u0144am",
 "RT @Spotify: This is epic. @lildickymessages got @justinbieber, @arianagrande, @halsey, @sanbenito, @edsheeran, @SnoopDogg, @ShawnMendes, @Kr \ u4046",
 "RT @biebercentineo: Justin : are we gonna die?  \ nLil dicky: you know bieber we might die  \ n \ nBTCH IM CRYING #EARTH #WeLikeTheEarth #WELIKEEART \ u4046",
 "RT @dreamsiinflate: #WeLikeTheEarth  \ u401ci am a fat fucking pig \ u401d okay brendon urie https: / /t.co /FdJmq31xZc",
 "Literally no one: \ n \ nMe in the past 4 hours: \ n \ nI'm a koala and I sleep all the time, so what, it's cute  \ ud83c \ udfb6 \ n \ n#WeLikeTheEarth #EdSheeranTheKoala",
 "RT @Yuuupthatsme: Mia \ u0144e \ u015b by \ u0107  \ u017cyraf \ u0105 #WeLikeTheEarth https: / /t.co /0kNCpU8o6q",
 "RT @jaguareffects: eu prestando aten \ u00e7 \ u00e3o no  \ u00e1udio pra identificar cada artista \ n \ n#WeLikeTheEarth https: / /t.co /0cDtiV4t1E" ] 

频率分析

从最新提取的前五个结果中,我们可以推断出以下信息

  • 这首歌是关于热爱地球的;
  • 包括 Lil Dicky 在内的几位著名音乐家正在推动这一 Twitter 趋势;
  • Ed Sheeran 扮作一只可爱的考拉;
  • 标签“EdSheeranTheKoala”!

通过查看有趣字段中的前 10 个项目,我们对数据有了初步了解。现在我们已经完成了一个简单但至关重要的练习——计算频率分布,我们可以看得更仔细。从频率开始是个好主意,因为它能为您提供前进的方向。

源代码片段

输出

[('lildickymessages', 104) , ('LeoDi' , 44) , ('ShawnMendes' , 33) , ('Halsey , 31) , ('ArianaGrande' , 30) , ('Justin Bieber , 49) , ('Spotify' , 46) , ('edsheeran' , 46) , ('sanbenito' , 45) , ('SnoopDogg' , 45)] 

[('WeLikeTheEarth' , 313) , ('4future' , 14) , ('19aprile' , 14) , ('EARTH' , 11) , ('fridaysforfuture' , 10) , ('EarthMusicVideo' , 3) , ('ConCalmaRemix' , 3) , ('Earth' , 3) , ('aliens' , 4) , ('AvengersEndgame' , 4)] 

更多关于趋势的活动

我们可以根据最新的频率分布进一步发展我们的结论

  • 更确定地说,这是一段带有“EarthMusicVideo”标签的 Lil Dicky 歌曲视频。
  • Leo Di 是一位环保主义者。因此,即使他不是音乐家,在这里看到他的名字也不足为奇。
  • 此外,我们可以说该视频是在一个星期五发布的,最有可能是在 4 月 19 日。
  • 我们已经能够收集到大量的知识。它非常强大。
  • 所有转推都围绕着特定的推文发生吗?让我们进一步检查数据,以寻找围绕消息活动的趋势。
  • 转推消息的“retweeted__status”功能包含有关原始推文内容和作者的丰富信息。

我们可以通过检查收藏计数和转推计数数据来确定消息的受欢迎程度。照片中有这么多名人,如果我们还提取推特用户的关注者计数,我们能否确定他们对 #WeLikeTheEarth 的支持是否影响了他们相当一部分的关注者?

retweet__count 字段提供了原始消息被转推的总次数。原始消息和任何后续的重新测试都应具有相同的信息。为了了解众多字段,请尝试使用一些示例消息和官方文档。

源代码片段

一张胜过千言万语的表格

让我们修改数据,使其更丰富、更好看,因为“外观很重要!”

源代码片段

分析所有上述使用的语言

根据我们的表格,Lil Dicky 的关注者回应最多;44.4% 的人喜欢他的原始推文。

  • 尽管歌手 Katy Perry 和 Degeneres 拥有庞大的 Twitter 关注者,但很少有粉丝做出回应。
  • Leo 在转推和点赞数量上获得最多,但只有 4.19% 的关注者喜欢他的第一条推文。

此外,这是 Lil Dicky 的音乐视频这一事实可能也导致了回应的鲜明对比。由于他对这项活动做出了重大贡献,Leo 仍然比 Katy 或 Ellen 获得了更多的关注。

数据能否分析出更多有趣的模式?我们可以从消息文本中区分出几种语言,所以让我们为每种语言做一个频率分布。

源代码片段

输出

107. ,  44. ,  14. ,  36. ,  34. ,   3. ,   4. ,   1. ,   4.]) ,
 array([ 0.  ,  1.3 ,  4.6 ,  3.4 ,  5.4 ,  6.5 ,  7.8 ,  4.1 , 10.4 , 11.7 , 13. ]),
 <a list of 10 Patch objects>)
(array([303. , 107. ,  44. ,  14. ,  36. ,  34. ,   3. ,   4. ,   1. ,   4.]) ,
 array([ 0.  ,  1.3 ,  4.6 ,  3.4 ,  5.4 ,  6.5 ,  7.8 ,  4.1 , 10.4 , 11.7 , 13. ]),
 <a list of 10 Patch objects>)

Real-Time Data Analysis from Social Media Data in Python

总结:发现想法

最终的直方图显示:大多数消息是英文的,其次是波兰语、意大利语和西班牙语。还有一些消息使用的是与 Facebook 无关的语言(lang = "und")。

这种知识为何有帮助?它可以帮助我们了解对该主题感兴趣的人群的“类别”(聚类)。为了回答诸如“拥有 iPhone 与 Android 是否会影响个人对这一趋势的倾向?”之类的问题,我们还可以分析 Twitter 用户推文中使用的设备类型。我将把它留给您作为一项新的练习!

这是一次多么激动人心的冒险啊!我们从最初的几乎一无所知,走了很长一段路。

从基于位置的比较到分析消息活动,再到发现跨语言和设备的模式,我们今天已经讲了很多。让我们给自己一个应得的鼓励吧!