Skip to main content
 首页 » 编程设计

Python将C头文件转换为dict

2024年10月25日12jyk

我有一个包含一系列类的 C 头文件,我正在尝试编写一个函数来获取这些类,并将它们转换为 python 字典。该文件的示例位于底部。

格式应该是这样的

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 等等,但我发现的大部分内容都是关于将行拆分为字典,而不是 n 深的“ block ”

我知道我必须遍历该文件,但是,我不确定将其转换为字典的最有效方法。 我在想我需要获取外部类及其相关的括号,然后对内部剩余的文本执行相同的操作。

如果这些都没有意义,那是因为我自己还没有完全理解这个过程哈哈

如果需要更多信息,我很乐意提供。

以下代码是我所想内容的快速模型... 它很可能损坏并且可能不起作用。但这是我正在考虑的过程

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 库目录中。

请您参考如下方法:

正如您检测到的那样,解析是进行转换所必需的。查看 PyParsing 包,这是一个相当易于使用的库,可在您的 Python 程序中实现解析。

编辑:这是识别非常极简语法所需要的一个非常具有象征意义的版本——有点像问题顶部的例子。它不会起作用,但它可能会让您朝着正确的方向前进:

from pyparsing import ZeroOrMore, OneOrMore, \ 
                      Keyword, Literal 
 
 
test_code = """ 
class CFGFunctions { 
  class ABC { 
    class AA { 
      file = "abc/aa/functions" 
      class myFuncName{ recompile = 1; }; 
    }; 
    class BB 
    { 
      file = "abc/bb/functions" 
      class funcName{ 
        recompile=1; 
      } 
    } 
  }; 
}; 
""" 
 
class_tkn       = Keyword('class') 
lbrace_tkn      = Literal('{') 
rbrace_tkn      = Literal('}') 
semicolon_tkn   = Keyword(';') 
assign_tkn      = Keyword(';') 
 
class_block     = ( class_tkn + identifier + lbrace_tkn + \ 
                    OneOrMore(class_block | ZeroOrMore(assignment)) + \ 
                    rbrace_tkn + semicolon_tkn \ 
                  ) 
 
def test_parser(test): 
    try: 
        results = class_block.parseString(test) 
        print test, ' -> ', results 
    except ParseException, s: 
        print "Syntax error:", s 
 
 
def main(): 
    test_parser(test_code) 
 
    return 0 
 
if __name__ == '__main__': 
    main() 

此外,此代码只是解析器 - 它不会生成任何输出。正如您在 PyParsing 文档中看到的那样,您可以稍后添加所需的操作。但第一步是识别您要翻译的内容。

最后一点:不要低估解析代码的复杂性......即使使用像 PyParsing 这样的库来处理大部分工作,也有很多方法可以陷入无限循环和其他解析便利.逐步实现!

编辑:有关 PyParsing 的一些信息来源是:

http://werc.engr.uaf.edu/~ken/doc/python-pyparsing/HowToUsePyparsing.html

http://pyparsing.wikispaces.com/

(特别有趣的是 http://pyparsing.wikispaces.com/Publications,其中有一长串关于 PyParsing 的文章——其中几篇是介绍性的)

http://pypi.python.org/pypi/pyparsing_helper是调试解析器的 GUI

在 stackoverflow 上还有一个“标签”Pyparsing,Paul McGuire(PyParsing 作者)似乎是这里的常客。

* 注意:* 来自 PaulMcG 在下面的评论中:Pyparsing 不再托管在 wikispaces.com 上。转到 github.com/pyparsing/pyparsing