2009-02-05 149 views
1

我正在写一个Applescript播放列表生成器。该过程的一部分是读取iTunes Library XML文件以获取用户库中所有流派的列表。这是Python实现,其工作方式,我想:翻译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调用并获得类似结果的东西。谢谢!

回答

3

为什么使用正则表达式来解析XML?为什么不使用正确的XML库? Python有一些像ElementTree这样的优秀实用工具,它使得DOM更容易走路,并且它产生友好的友好对象而不是无类型的字符串。

下面是使用AppleScript解析XML的一些方法:

Applescript XML Parser(因为老虎显然可用)

XML Tools you can also use with Applescript

记住,就像AppleScript的可以连接到iTunes,它可以挂接到其它安装像这些公用事业。

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

+0

+1。用于解析XML的正则表达式是错误的。有一千件事情可以而且会打破。为什么大家会继续坚持使用正则表达式作为解决它无法覆盖的文本解析问题的第一个手段? – bobince 2009-02-05 12:23:06

0

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

看py2app:

py2app,就像py2exe,但针对的Mac OS

See

0

如果您已经在AppleScript的工作,为什么不干脆直接问的iTunes?

tell application "iTunes" to get genre of every track of library playlist 1