2009-02-05 148 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