使用正則表達式分離成對:
In [1]: import re
In [2]: txt = '(((st 8) (pitch 67) (dur 4) (keysig 1) (timesig 12) (fermata 0))((st 12) (pitch 67) (dur 8) (keysig 1) (timesig 12) (fermata 0)))'
In [3]: [p.split() for p in re.findall('\w+\s+\d+', txt)]
Out[3]: [['st', '8'], ['pitch', '67'], ['dur', '4'], ['keysig', '1'], ['timesig', '12'], ['fermata', '0'], ['st', '12'], ['pitch', '67'], ['dur', '8'], ['keysig', '1'], ['timesig', '12'], ['fermata', '0']]
然後使之成爲一個詞典:
dct = {}
for p in data:
if not p[0] in dct.keys():
dct[p[0]] = [p[1]]
else:
dct[p[0]].append(p[1])
其結果是:
In [10]: dct
Out[10]: {'timesig': ['12', '12'], 'keysig': ['1', '1'], 'st': ['8', '12'], 'pitch': ['67', '67'], 'dur': ['4', '8'], 'fermata': ['0', '0']}
印刷:
print 'time pitch duration keysig timesig fermata'
for t in range(len(dct['st'])):
print dct['st'][t], dct['pitch'][t], dct['dur'][t],
print dct['keysig'][t], dct['timesig'][t], dct['fermata'][t]
正確的格式就留給讀者做練習...
不[解析S-表達式在Python(http://stackoverflow.com/q/3182594)幫助? –
謝謝,請看看。 – qua
爲什麼不使用lisp將其轉換爲另一種格式? – Marcin