1

我正在编写一个 Applescript 播放列表生成器。该过程的一部分是读取 iTunes 库 XML 文件以获取用户库中所有流派的列表。这是 python 实现,它可以按我的意愿工作:

    #!/usr/bin/env python

# script to get all of the genres from itunes

import re,sys,sets


## Boosted from the internet to handle HTML entities in Genre names
def unescape(text):
    def fixup(m):
        text = m.group(0)
        if text[:2] == "&#":
            # character reference
            try:
                if text[:3] == "&#x":
                    return unichr(int(text[3:-1], 16))
                else:
                    return unichr(int(text[2:-1]))
            except ValueError:
                pass
        else:
            # named entity
            try:
                text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
            except KeyError:
                pass
        return text # leave as is
    return re.sub("&#?\w+;", fixup, text)


# probably faster to use a regex than to try to walk
# the entire xml document and aggregate the genres
try:
    xml_path = "/Users/%s/Music/iTunes/iTunes Music Library.xml" % sys.argv[1]
except:
    print '\tUsage: python '+sys.argv[0]+' <your OSX username>'
    raise SystemExit

pattern = "<key>Genre</key><string>([^<]+)</string>" 

try:
    xml = file(xml_path,'r').read()
except:
    print '\tUnable to load your iTunes Library XML file'
    raise SystemExit

matches = re.findall(pattern,xml)
uniques = map(unescape,list(sets.Set(matches)))
## need to write these out somewhere so the applescript can read them
sys.stdout.write('|'.join(uniques))
raise SystemExit

问题是,我希望 Applescript 是独立的,并且不需要存在这个附加文件(我计划将它提供给其他人)。而且,据我所知,Applescript 不提供开箱即用的任何类型的正则表达式功能。我可以遍历库中的每个曲目以获取所有流派,但这是一个非常长的过程,我在构建播放列表时已经做过一次。所以,我正在寻找替代品。

由于 Applescript 允许我运行 shell 脚本并捕获结果,我想我可以使用某种类型的 shell 命令来完成相同的行为,无论是 grep、perl 还是其他命令。我的 *nix 命令行技能非常生疏,我正在寻找一些指导。

所以,简而言之,我想找到一种方法将上面的 python 代码翻译成我可以直接从 shell 调用的东西,并得到类似的结果。谢谢!

4

3 回答 3

3

为什么要使用正则表达式来解析 XML?为什么不使用适当的 XML 库?Python 有一些很棒的实用程序,比如 ElementTree,它们可以让遍历 DOM 变得更加容易,并且它会生成漂亮、友好的对象,而不是无类型的字符串。

以下是一些使用 Applescript 解析 XML 的方法:

Applescript XML 解析器(显然自 Tiger 起可用)

您也可以与 Applescript 一起使用的 XML 工具

请记住,就像 Applescript 可以挂接到 iTunes 一样,它也可以挂接到其他已安装的实用程序,例如这些。

最后,为什么不直接用 Python 编写整个东西,因为它有更好的开发工具用于调试并且运行速度更快。如果您正在运行 Leopard,则您已经预装了 Python 2.5.1。

于 2009-02-05T07:30:52.307 回答
0

创建一个独立的应用程序是解决方案吗?

看看py2app:

py2app,与 py2exe 类似,但针对 Mac OS

于 2009-02-05T11:58:02.093 回答
0

如果您已经在使用 AppleScript,为什么不直接询问 iTunes?

tell application "iTunes" to get genre of every track of library playlist 1
于 2009-02-08T12:13:07.083 回答