【发布时间】:2014-07-30 00:17:20
【问题描述】:
我有一个包含一系列类的 C 头文件,我正在尝试编写一个函数来获取这些类,并将它们转换为 python dict。该文件的样本位于底部。
格式类似于
class CFGFunctions {
class ABC {
class AA {
file = "abc/aa/functions"
class myFuncName{ recompile = 1; };
};
class BB
{
file = "abc/bb/functions"
class funcName{
recompile=1;
}
}
};
};
我希望把它变成类似的东西
{CFGFunctions:{ABC:{AA:"myFuncName"}, BB:...}}
# Or
{CFGFunctions:{ABC:{AA:{myFuncName:"string or list or something"}, BB:...}}}
最后,我的目标是获取文件路径字符串(实际上是文件夹的路径......但无论如何),以及与文件/文件夹路径相同的类中的类名。
我看过 SO、google 等,但我发现的大部分内容都是关于将行拆分为 dicts,而不是 n-deep 'blocks'
我知道我必须遍历文件,但是,我不确定将其转换为 dict 的最有效方法。 我想我需要获取外部类及其相关括号,然后对剩余的文本执行相同操作。
如果这些都没有意义,那是因为我自己还没有完全理解这个过程哈哈
如果需要更多信息,我很乐意提供。
以下代码是我所想的快速模型... 它很可能是BROKEN并且可能不工作。但这是我正在考虑的过程
def get_data():
fh = open('CFGFunctions.h', 'r')
data = {} # will contain final data model
# would probably refactor some of this into a function to allow better looping
start = "" # starting class name
brackets = 0 # number of brackets
text= "" # temp storage for lines inside block while looping
for line in fh:
# find the class (start
mt = re.match(r'Class ([\w_]+) {', line)
if mt:
if start == "":
start = mt.group(1)
else:
# once we have the first class, find all other open brackets
mt = re.match(r'{', line)
if mt:
# and inc our counter
brackets += 1
mt2 = re.match(r'}', line)
if mt2:
# find the close, and decrement
brackets -= 1
# if we are back to the initial block, break out of the loop
if brackets == 0:
break
text += line
data[start] = {'tempText': text}
====
示例文件
class CfgFunctions {
class ABC {
class Control {
file = "abc\abc_sys_1\Modules\functions";
class assignTracker {
description = "";
recompile = 1;
};
class modulePlaceMarker {
description = "";
recompile = 1;
};
};
class Devices
{
file = "abc\abc_sys_1\devices\functions";
class registerDevice { recompile = 1; };
class getDeviceSettings { recompile = 1; };
class openDevice { recompile = 1; };
};
};
};
编辑: 如果可能的话,如果我必须使用一个包,我想把它放在程序目录中,而不是一般的 python libs 目录中。
【问题讨论】:
-
使用
pycparser之类的东西将其解析为 AST,然后(合理地)从那里开始。 -
你想让它像 LISP lang。
-
感谢您的建议 :) 有点跑题了,您知道是否可以将软件包“安装”在与项目相同的目录中? (而不是 python 库文件)
标签: python file parsing dictionary block