Applescript プレイリスト ジェネレーターを作成しています。プロセスの一部として、iTunes Library 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 はすぐに使用できる正規表現機能を提供していません。ライブラリ内の各トラックをループしてすべてのジャンルを取得することもできますが、これは非常に長いプロセスであり、プレイリストを作成するときにすでに 1 回行っています。そこで、代替品を探しています。
Applescript を使用すると、シェル スクリプトを実行して結果をキャプチャできるため、grep、perl、またはその他のシェル コマンドを使用して同じ動作を実現できると思います。私の *nix コマンド ライン スキルは非常に使い慣れていないため、ガイダンスを探しています。
要するに、上記の python コードをシェルから直接呼び出して同様の結果を得ることができるものに変換する方法を見つけたいと思います。ありがとう!