4

我想在 python 中解析一个 erlang 配置文件。有它的模块吗?该配置文件包含;

[{webmachine, [
 {bind_address, "12.34.56.78"},
 {port, 12345},
 {document_root, "foo/bar"}
]}].
4

2 回答 2

4

未经测试且有点粗糙,但在您的示例中“有效”

import re
from ast import literal_eval

input_string = """
[{webmachine, [ 
 {bind_address, "12.34.56.78"}, 
 {port, 12345}, 
 {document_root, "foo/bar"} 
]}]
"""

# make string somewhat more compatible with Python syntax:
compat = re.sub('([a-zA-Z].*?),', r'"\1":', input_string)

# evaluate as literal, see what we get
res = literal_eval(compat)

[{'webmachine': [{'bind_address': '12.34.56.78'}, {'port': 12345},
{'document_root': 'foo/bar'}]}]

然后,您可以将字典列表“汇总”为一个简单的dict,例如:

dict(d.items()[0] for d in res[0]['webmachine'])

{'bind_address': '12.34.56.78', 'port': 12345, 'document_root':
'foo/bar'}
于 2012-09-06T10:26:56.113 回答
4

您可以使用 etf 库在 python https://github.com/machinezone/python_etf中解析 erlang 术语

于 2015-06-10T14:52:17.637 回答