百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程文章 > 正文

果粉有福了!5分钟学会用Python统计自己最爱听的音乐

qiyuwang 2024-10-11 18:23 9 浏览 0 评论

作为一个最狂热的果粉,喜欢用苹果来播放自己最爱的音乐,随时让音乐充满自己的生活。想统计自己哪些音乐才是自己最爱吗?想知道哪些音乐是自己第一次听见就相伴终身吗?下面用Python来完成您的心愿。

下面的实战项目在iTunes播放列表文件中查找重复的乐曲音轨(重复的频率越多就是你最爱的音乐:-)),并绘制各种统计数据,如音轨长度和评分。你可以从查看iTunes播放列表格式开始,然后学习如何用Python提取这些文件的信息。为了绘制这些数据,要用到matplotlib库。

在这个项目中,我们将学习以下主题:

  • XML和属性列表(p-list)文件;
  • Python列表和字典;
  • 使用Python的set对象;
  • 使用numpy数组;
  • 直方图和散点图;
  • 用matplotlib库绘制简单的图;
  • 创建和保存数据文件。

iTunes播放列表文件剖析

iTunes资料库中的信息可以导出为播放列表文件(在iTunes中选择File?Library?Export Playlist)。播放列表文件以可扩展标记语言(XML)写成,这是一种基于文本的语言,旨在分层表示基于文本的信息。它包括一些用户定义的标签所构成的树状集合,标签形如<MyTag>,每个标签可以有一些属性和子标签,其中包含附加的信息。

如果在文本编辑器中打开一个播放列表文件,你会看到类似这样的简化版本:

Bash
  <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www
  apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict><key>Major Version</key><integer>1</integer>
  <key>Minor Version</key><integer>1</integer>
  --snip--
⑤ <key>Tracks</key>
  <dict>
  <key>2438</key>
  <dict>
  <key>Track ID</key><integer>2438</integer>
  <key>Name</key><string>Yesterday</string>
  <key>Artist</key><string>The Beatles</string>
  <key>Composer</key><string>Lennon [John], McCartney [Paul]</string>
  <key>Album</key><string>Help!</string>
  </dict>
  --snip--
  </dict><key>Playlists</key>
  <array>
  <dict>
  <key>Name</key><string>Now</string>
  <key>Playlist ID</key><integer>21348</integer>
  --snip--
  <array>
  <dict>
  <key>Track ID</key><integer>6382</integer>
  </dict>
  --snip--
  </array>
  </dict>
  </array>
  </dict>
  </plist>

属性列表(P-list)文件将对象表示为字典,<dict> 和 <key> 标签与这种方式有关。字典是把键和值关联起来的数据结构,让查找值变得容易。属性列表文件使用字典的字典,其中和键关联的值往往自身又是另一个词典(甚至一个字典列表)。

<xml>标签确定文件为XML文件。在这个开始标签之后,文档类型定义(DTD)定义了XML文档的结构①。如你所见,苹果在该标签中的统一资源定位符(URL)中定义了这种结构。

在②行,文件声明了顶层<plist>标签,其唯一子元素是字典<dict> ③。该字典包含了各种键,在④行,包括Major Version、Minor Version,等等,但我们的兴趣在⑤行的Tracks键。注意,该键对应的值也是一个字典,它将整数的音轨ID映射到另一个字典,其中包含Name、Artist等元素。音乐收藏中的每个音轨都有唯一的音轨ID键。

播放列表顺序在⑥行由Playlists定义,它是顶层字典的一个子节点。

所需模块

在这个项目中,我们用内置模块plistlib来读取播放列表文件。我们还用matplotlib库来绘图,用numpy的数组来存储数据。

代码

该项目的目标是找到你的音乐收藏中的重复乐曲,确定播放列表之间共同的音轨,绘制音轨时长的分布图,以及歌曲评分和时长之间的关系图。

随着音乐收藏不断增加,你总会遇到重复的乐曲。为了确定重复的乐曲,查找与Tracks键关联的字典中的名称(前面讨论过),找到重复的乐曲,并用音轨长度作为附加准则来检测重复的乐曲,因为名称相同、但长度不同的音轨,可能是不一样的。

要找到两个或多个播放列表之间共同的音轨,你需要将音乐收藏导出为播放列表文件,收集每个播放列表的音轨名称,作为集合进行比较,通过发现集合的交集来找到共同的音轨。

在收集音乐收藏数据的同时,我们将使用强大的matplotlib(http://matplotlib.org/)绘图软件包来创建一些图,该软件包由已故的John Hunter开发。我们可以绘制直方图来显示音轨时长的分布,绘制散点图来比较乐曲评分与长度。

要查看完整的项目代码,请直接跳到1.4节。

查找重复

首先可以用findDuplicates()方法来查找重复的曲目,如下所示:

Bash
  def findDuplicates(fileName):
  print('Finding duplicate tracks in %s...' % fileName)
  # read in a playlist
① plist = plistlib.readPlist(fileName)
  # get the tracks from the Tracks dictionary
② tracks = plist['Tracks']
  # create a track name dictionary
③ trackNames = {}
  # iterate through the tracksfor trackId, track in tracks.items():
  try:
⑤ name = track['Name']
  duration = track['Total Time']
  # look for existing entriesif name in trackNames:
  # if a name and duration match, increment the count
  # round the track length to the nearest secondif duration//1000 == trackNames[name][0]//1000:
  count = trackNames[name][1]
⑧ trackNames[name] = (duration, count+1)
  else:
  # add dictionary entry as tuple (duration, count)
⑨ trackNames[name] = (duration, 1)
  except:
  # ignore
  pass

在①行,readPlist()方法接受一个p-list文件作为输入,并返回顶层字典。在②行,访问Tracks字典,在③行,创建一个空的字典,用来保存重复的乐曲。在④行,开始用items()方法迭代Tracks字典,这是Python在迭代字典时取得键和值的常用方法。

在⑤行,取得字典中每个音轨的名称和时长。用in关键字,检查当前乐曲的名称是否已在被构建的字典中⑥。如果是这样的,程序检查现有的音轨和新发现的音轨长度是否相同⑦,用//操作符,将每个音轨长度除以1000,由毫秒转换为秒,并四舍五入到最接近的秒,以进行检查(当然,这意味着,只有毫秒差异的两个音轨被认为是相同的)。如果确定这两个音轨长度相等,就取得与name关联的值,这是(duration,count)元组,并在⑧行增加计数。如果这是程序第一次遇到的音轨名称,就创建一个新条目,count为1⑨。

将代码的主for循环放在try语句块中,这是因为一些乐曲音轨可能没有定义乐曲名称。在这种情况下,跳过该音轨,在except部分只包含pass(什么也不做)。

提取重复

利用以下代码,提取重复的音轨:

Bash
  # store duplicates as (name, count) tuples
① dups = []
  for k, v in trackNames.items():
② if v[1] > 1:
  dups.append((v[1], k))
  # save duplicates to a fileif len(dups) > 0:
  print("Found %d duplicates. Track names saved to dup.txt" % len(dups))
  else:
  print("No duplicate tracks found!")
④ f = open("dups.txt", "w")
  for val in dups:
⑤ f.write("[%d] %s\n" % (val[0], val[1]))
  f.close()

在①行,创建一个空列表,保存重复乐曲。接下来,迭代遍历trackNames字典,如果count(用v[1]访问,因为它是元组的第二个元素)大于1②,则将元组(name,count)添加到列表中。在③行,程序打印它找到的信息,然后用open()方法将信息存入文件④。在⑤行,迭代遍历dups列表,写下重复的条目。

查找多个播放列表中共同的音轨

现在,让我们来看看如何找到多个播放列表中共同的乐曲音轨:

Bash
  def findCommonTracks(fileNames):
  # a list of sets of track names
① trackNameSets = []
  for fileName in fileNames:
  # create a new set
② trackNames = set()
  # read in playlist
③ plist = plistlib.readPlist(fileName)
  # get the tracks
  tracks = plist['Tracks']
  # iterate through the tracks
  for trackId, track in tracks.items():
  try:
  # add the track name to a set
④ trackNames.add(track['Name'])
  except:
  # ignore
  pass
  # add to list
⑤ trackNameSets.append(trackNames)
  # get the set of common tracks
⑥ commonTracks = set.intersection(*trackNameSets)
  # write to file
  if len(commonTracks) > 0:
⑦ f = open("common.txt", "w")
  for val in commonTracks:
  s = "%s\n" % val
⑧ f.write(s.encode("UTF-8"))
  f.close()
  print("%d common tracks found. "
  "Track names written to common.txt." % len(commonTracks))
  else:
  print("No common tracks!")

首先,将播放列表的文件名列表传入findCommonTracks(),它创建一个空列表①,保存从每个播放列表创建的一组对象。然后程序迭代遍历列表中的每个文件。对每个文件,创建一个名为trackNames的Python set对象②,然后像在findDuplicates()中一样,用plistlib读入文件③,取得Tracks字典。接下来,迭代遍历该字典中的每个音轨,并添加trackNames对象④。程序读完一个文件中的所有音轨后,将这个集合加入trackNameSets⑤。

在⑥行,使用set.intersection()方法来获得集合之间共同音轨的集合(用Python*的运算符来展开参数列表)。如果程序发现集合之间的共同音轨,就将音轨名称写入一个文件。在⑦行,打开文件,接下来的两行代码完成写入。使用encode()来格式化输出,确保所有Unicode字符都正确处理⑧。

收集统计信息

接下来,用plotStats()方法,针对这些音轨名称收集统计信息:

Bash
  def plotStats(fileName):
  # read in a playlist
① plist = plistlib.readPlist(fileName)
  # get the tracks from the playlist
  tracks = plist['Tracks']
  # create lists of song ratings and track durations
② ratings = []
  durations = []
  # iterate through the tracks
  for trackId, track in tracks.items():
  try:
③ ratings.append(track['Album Rating'])
  durations.append(track['Total Time'])
  except:
  # ignore
  pass

  # ensure that valid data was collectedif ratings == [] or durations == []:
  print("No valid Album Rating/Total Time data in %s." % fileName)
  return

这里的目标是收集评分和音轨时长,然后画一些图。在①行和接下来的代码行中,读取了播放列表文件,并访问Tracks字典。接下来,创建两个空列表,保存评分和时长②(在iTunes播放列表中,评分是一个整数,范围是[0,100])。迭代遍历音轨,在③行,将评分和时长添加到相应的列表中。最后,在④行检查完整性,确保从播放列表文件收集了有效数据。

绘制数据

我们已准备好绘制一些数据了。

Bash
  # scatter plot
① x = np.array(durations, np.int32)
  # convert to minutes
② x = x/60000.0
③ y = np.array(ratings, np.int32)
④ pyplot.subplot(2, 1, 1)
⑤ pyplot.plot(x, y, 'o')
⑥ pyplot.axis([0, 1.05*np.max(x), -1, 110])
⑦ pyplot.xlabel('Track duration')
⑧ pyplot.ylabel('Track rating')

  # plot histogram
  pyplot.subplot(2, 1, 2)
⑨ pyplot.hist(x, bins=20)
  pyplot.xlabel('Track duration')
  pyplot.ylabel('Count')

  # show plot
⑩ pyplot.show()

在①行,利用numpy.array()(在代码中作为np导入),将音轨时长数据放到32位整数数组中。然后在②行,利用numpy,将一个操作应用于数组中的每个元素。在这个例子中,将每个以毫秒为单位的时长值除以值60×1000。在③行,将乐曲评分保存另一个numpy数组y中。

用matplotlib在同一图像上绘制两张图。在④行,提供给subplot()的参数(即,(2, 1, 1))告诉matplotlib,该图应该有两行(2)一列(1),且下一个点应在第一行(1)。在⑤行,通过调用plot()创建一个点,并且o告诉matplotlib用圆圈来表示数据。

在⑥行,为 x 轴和 y 轴设置略微大一点儿的范围,以便在图和轴之间留一些空间。在⑦和⑧行,为 x 轴和 y 轴设置说明文字。

现在用matplotlib的方法hist(),在同一张图中的第二行中,绘制时长直方图⑨。bins参数设置了数据分区的个数,其中每分区用于添加在这个范围内的计数。最后,调用show()⑩,matplotlib在新窗口中显示出漂亮的图。

命令行选项

现在,我们来看看该程序的main()方法如何处理命令行参数:

Bash
  def main():
  # create parser
  descStr = """
  This program analyzes playlist files (.xml) exported from iTunes.
  """
① parser = argparse.ArgumentParser(description=descStr)
  # add a mutually exclusive group of arguments
② group = parser.add_mutually_exclusive_group()

  # add expected arguments
③ group.add_argument('--common', nargs='*', dest='plFiles', required=False)
④ group.add_argument('--stats', dest='plFile', required=False)
⑤ group.add_argument('--dup', dest='plFileD', required=False)

  # parse args
⑥ args = parser.parse_args()

  if args.plFiles:
  # find common tracks
  findCommonTracks(args.plFiles)
  elif args.plFile:
  # plot stats
  plotStats(args.plFile)
  elif args.plFileD:
  # find duplicate tracks
  findDuplicates(args.plFileD)
  else:
⑦ print("These are not the tracks you are looking for.")

本书的大多数项目都有命令行参数。不要尝试手工分析它们并搞得一团糟,要将这个日常的任务委派给Python的argparse模块。在①行,为此创建了一个ArgumentParser对象。该程序可以做三件不同的事情,如发现播放列表之间的共同音轨,绘制统计数据,或发现播放列表中重复的曲目。但是,一个时间程序只能做其中一件事,如果用户决定同时指定两个或多个选项,我们不希望它崩溃。argparse模块为这个问题提供了一个解决方案,即相互排斥的参数分组。在②行,用parser.add_mutually_exclusive_group()方法来创建这样一个分组。

在③、④和⑤行,指定了前面提到的命令行选项,并输入应该将解析值存入的变量名(args.plFiles、args.plFile和args.plFileD),实际解析在⑥行完成。参数解析后,就将它们传递给相应的函数,findCommonTracks()、plotStats()和findDuplicates(),本章前面讨论过这些函数。

要查看参数是否被解析,就测试args中相应的变量名。例如,如果用户没有使用--common选项(该选项找出播放列表之间的共同音轨),解析后args.plFiles应该设置为None。

在⑦行,处理用户未输入任何参数的情况。

完整代码

下面是完整的程序。在https://github.com/electronut/pp/tree/master/playlist/,你也可以找到本项目的代码和一些测试数据。

Bash
import re, argparse
import sys
from matplotlib import pyplot
import plistlib
import numpy as np

def findCommonTracks(fileNames):
 """
 Find common tracks in given playlist files,
 and save them to common.txt.
 """
 # a list of sets of track names
 trackNameSets = []
 for fileName in fileNames:
 # create a new set
 trackNames = set()
 # read in playlist
 plist = plistlib.readPlist(fileName)
 # get the tracks
 tracks = plist['Tracks']
 # iterate through the tracks
 for trackId, track in tracks.items():
 try:
 # add the track name to a set
 trackNames.add(track['Name'])
 except:
 # ignore
 pass
 # add to list
 trackNameSets.append(trackNames)
 # get the set of common tracks
 commonTracks = set.intersection(*trackNameSets)
 # write to file
 if len(commonTracks) > 0:
 f = open("common.txt", 'w')
 for val in commonTracks:
 s = "%s\n" % val
 f.write(s.encode("UTF-8"))
 f.close()
 print("%d common tracks found. "
 "Track names written to common.txt." % len(commonTracks))
 else:
 print("No common tracks!")

 def plotStats(fileName):
 """
 Plot some statistics by reading track information from playlist.
 """
 # read in a playlist
 plist = plistlib.readPlist(fileName)
 # get the tracks from the playlist
 tracks = plist['Tracks']
 # create lists of song ratings and track durations
 ratings = []
 durations = []
 # iterate through the tracks
 for trackId, track in tracks.items():
 try:
 ratings.append(track['Album Rating'])
 durations.append(track['Total Time'])
 except:
 # ignore
 pass
 # ensure that valid data was collected
 if ratings == [] or durations == []:
 print("No valid Album Rating/Total Time data in %s." % fileName)
 return

 # scatter plot
 x= np.array(durations, np.int32)
 # convert to minutes
 x = x/60000.0
 y = np.array(ratings, np.int32)
 pyplot.subplot(2, 1, 1)
 pyplot.plot(x, y, 'o')
 pyplot.axis([0, 1.05*np.max(x), -1, 110])
 pyplot.xlabel('Track duration')
 pyplot.ylabel('Track rating')

 # plot histogram
 pyplot.subplot(2, 1, 2)
 pyplot.hist(x, bins=20)
 pyplot.xlabel('Track duration')
 pyplot.ylabel('Count')
 # show plot
 pyplot.show()

 def findDuplicates(fileName):
 """
 Find duplicate tracks in given playlist.
 """
 print('Finding duplicate tracks in %s...' % fileName)
 # read in playlist
 plist = plistlib.readPlist(fileName)
 # get the tracks from the Tracks dictionary
 tracks = plist['Tracks']
 # create a track name dictionary
 trackNames = {}
 # iterate through tracks
 for trackId, track in tracks.items():
 try:
 name = track['Name']
 duration = track['Total Time']
 # look for existing entries
 if name in trackNames:
 # if a name and duration match, increment the count
 # round the track length to the nearest second
 if duration//1000 == trackNames[name][0]//1000:
 count = trackNames[name][1]
 trackNames[name] = (duration, count+1)
 else:
 # add dictionary entry as tuple (duration, count)
 trackNames[name] = (duration, 1)
 except:
 # ignore
 pass
 # store duplicates as (name, count) tuples
 dups = []
 for k, v in trackNames.items():
 if v[1] > 1:
 dups.append((v[1], k))
 # save duplicates to a file
 if len(dups) > 0:
 print("Found %d duplicates. Track names saved to dup.txt" % len(dups))
 else:
 print("No duplicate tracks found!")
 f = open("dups.txt", 'w')
 for val in dups:
 f.write("[%d] %s\n" % (val[0], val[1]))
 f.close()

 # gather our code in a main() function
 def main():
 # create parser
 descStr = """
 This program analyzes playlist files (.xml) exported from iTunes.
 """
 parser = argparse.ArgumentParser(description=descStr)
 # add a mutually exclusive group of arguments
 group = parser.add_mutually_exclusive_group()

 # add expected arguments
 group.add_argument('--common', nargs='*', dest='plFiles', required=False)
 group.add_argument('--stats', dest='plFile', required=False)
 group.add_argument('--dup', dest='plFileD', required=False)

 # parse args
 args = parser.parse_args()

 if args.plFiles:
 # find common tracks
 findCommonTracks(args.plFiles)
 elif args.plFile:
 # plot stats
 plotStats(args.plFile)
 elif args.plFileD:
 # find duplicate tracks
 findDuplicates(args.plFileD)
 else:
 print("These are not the tracks you are looking for.")

# main method
if __name__ == '__main__':
 main()

1.5 运行程序

下面是该程序的运行示例:

Bash
$ python playlist.py --common test-data/maya.xml test-data/rating.xml

下面是输出:

Bash
5 common tracks found. Track names written to common.txt.
$ cat common.txt
God Shuffled His Feet
Rubric
Floe
Stairway To Heaven
Pi's Lullaby
moksha:playlist mahesh$

现在,让我们绘制这些音轨的一些统计数据。

Bash
$ python playlist.py --stats test-data/rating.xml

图1-1展示了这次运行的输出。

小结

在这个项目中,我们开发了一个程序,分析了iTunes播放列表。在这个过程中,我们学习了一些有用的Python结构。在接下来的项目中,你将基于这里介绍的一些基础知识,探索各种有趣的主题,深入地研究Python。

相关推荐

程序员都用什么电脑?适合编程笔记本电脑推荐

适合程序员的笔记本电脑首先应该满足小巧轻便这个需求,然后才是性能因素,一个标准的程序员必定能够随时随地改BUG,所以可以优先考虑苹果MacBookPro,由于其MacOS就是Linux内核,做开...

Linux(debian)内核编译(二)虚拟网卡实例

2.10.虚拟网卡TUN/TAP...

老毛子要上天 冬天竟然拿矿机当暖气

2017-12-2814:10:55作者:李鑫我们都知道矿机在实际工作当中会产生出大量的热能,近日俄罗斯就有人用Comino挖矿电脑来充当暖气的效果,这台电脑不需要特别安装,也没有多余的接口,同样...

qemu linux内核(5.10.209)开发环境搭建

版本信息宿主机:ubuntu20.04.6LTS(FocalFossa)虚拟机:ubuntu20.04.6LTS(FocalFossa)安装宿主机的步骤省略,和一般的在vmware中安...

Ubuntu 16.04 LTS现已正式支持IBM LinuxONE与z Systems

4月22号的时候,Canonical很高兴地宣布了Ubuntu16.04LTS(XenialXerus)已正式支持IBMzSystems和LinuxONE大型机的消息。该长期支持版本经历了六...

号称最强大深度学习笔电,雷蛇推出Lambda Tensorbook笔记本电脑

IT之家4月13日消息,深度学习公司Lambda与雷蛇合作,发布了新的LambdaTensorbook笔记本电脑,号称是世界上为深度学习设计的最强大的笔记本电脑,可以使用Linux...

电脑连 WiFi 全攻略!3 步搞定 + 疑难解答

电脑搜不到WiFi?输对密码却连不上?看视频卡、打游戏延迟高?别慌!不管你用Win/Mac还是Linux,这篇保姆级教程从连接步骤到故障排查全覆盖,10分钟让你告别“网络黑洞”!一、基础连...

linux 网卡bond模式

如何进行Linux网络绑定网络绑定简介在Debian10Buster(DHCP)上配置有线和无线网络绑定...

在 Ubuntu Server 上配置静态 IP 地址

Ubuntu17.10之前版本编辑/etc/network/interfaces文件重启网络服务或重启服务器来应用新的配置...

爬虫搞崩网站后,程序员自制“Zip炸弹”反击,6刀服务器成功扛住4.6万请求

...

Linux网络运维脚本实战示例:配置下发

在Linux网络运维场景中,自动化配置下发是提高效率的关键。一个示例展示如何编写一个Shell脚本,用于远程批量部署网络配置到多台服务器。本示例将使用SSH无密码登录和Ansible自动化工具来简化和...

KVM 虚拟机网络连接异常的排查方法

#KVM虚拟机网络连接异常的排查方法当KVM虚拟机出现网络连接问题时,可以按照以下系统化的方法进行排查和解决:##一、基础网络检查###1.检查虚拟机网络状态```bash#在虚拟机内部检...

技术宅教你linux开发板直连电脑ubuntu

1:我使用的是笔记本,台式机类似。原理:和开发板挂载到路由器或者交换机不一样。我们通过笔记本电脑直连,是将笔记本的物理网卡作为一个桥梁,把开发板和虚拟机ubuntu连接在一起。连接好以后可以使用NFS...

Ubuntu 25.04发行版登场:Linux 6.14内核,带来多项技术革新

IT之家4月18日消息,科技媒体linuxiac昨日(4月17日)发布博文,报道称代号为PluckyPuffin的Ubuntu25.04发行版正式上线,搭载最新Linu...

【故障解决】麒麟系统右下角网络图标取消显示叹号

原文链接:【故障解决】麒麟系统右下角网络图标取消显示叹号...

取消回复欢迎 发表评论: