我正在寫一個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調用並獲得類似結果的東西。謝謝!
+1。用於解析XML的正則表達式是錯誤的。有一千件事情可以而且會打破。爲什麼大家會繼續堅持使用正則表達式作爲解決它無法覆蓋的文本解析問題的第一個手段? – bobince 2009-02-05 12:23:06