用Python解析Lisp文件 [英] Parsing a lisp file with Python
本文介绍了用Python解析Lisp文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下lisp文件,该文件来自 UCI机器学习数据库.我想使用python将其转换为平面文本文件.典型的行如下所示:
I have the following lisp file, which is from the UCI machine learning database. I would like to convert it into a flat text file using python. A typical line looks like this:
(1 ((st 8) (pitch 67) (dur 4) (keysig 1) (timesig 12) (fermata 0))((st 12) (pitch 67) (dur 8) (keysig 1) (timesig 12) (fermata 0)))
我想将其解析为一个文本文件,例如:
I would like to parse this into a text file like:
time pitch duration keysig timesig fermata
8 67 4 1 12 0
12 67 8 1 12 0
是否有一个python模块可以智能地对此进行解析?这是我第一次看到Lisp.
Is there a python module to intelligently parse this? This is my first time seeing lisp.
推荐答案
As shown in this answer, pyparsing appears to be the right tool for that:
inputdata = '(1 ((st 8) (pitch 67) (dur 4) (keysig 1) (timesig 12) (fermata 0))((st 12) (pitch 67) (dur 8) (keysig 1) (timesig 12) (fermata 0)))'
from pyparsing import OneOrMore, nestedExpr
data = OneOrMore(nestedExpr()).parseString(inputdata)
print data
# [['1', [['st', '8'], ['pitch', '67'], ['dur', '4'], ['keysig', '1'], ['timesig', '12'], ['fermata', '0']], [['st', '12'], ['pitch', '67'], ['dur', '8'], ['keysig', '1'], ['timesig', '12'], ['fermata', '0']]]]
出于完整性考虑,这是格式化结果的方式(使用文本表):
For the completeness' sake, this is how to format the results (using texttable):
from texttable import Texttable
tab = Texttable()
for row in data.asList()[0][1:]:
row = dict(row)
tab.header(row.keys())
tab.add_row(row.values())
print tab.draw()
+---------+--------+----+-------+-----+---------+
| timesig | keysig | st | pitch | dur | fermata |
+=========+========+====+=======+=====+=========+
| 12 | 1 | 8 | 67 | 4 | 0 |
+---------+--------+----+-------+-----+---------+
| 12 | 1 | 12 | 67 | 8 | 0 |
+---------+--------+----+-------+-----+---------+
要将数据转换回lisp表示法:
To convert that data back to the lisp notation:
def lisp(x):
return '(%s)' % ' '.join(lisp(y) for y in x) if isinstance(x, list) else x
d = lisp(d[0])
这篇关于用Python解析Lisp文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文