【问题标题】:Converting a parse tree to a string将解析树转换为字符串
【发布时间】:2014-10-07 21:14:41
【问题描述】:

我使用 PycParser 为 C 函数生成抽象语法树,但我仍在尝试弄清楚如何将解析树转换为字符串:

from pycparser import c_parser

src =  '''
int hello(a, b){
    return a + b;
}
'''
ast = c_parser.CParser().parse(src)
aString = ast.show()
print(aString) #This prints "None" instead of printing the parse tree

是否可以从已经生成的解析树中生成一个字符串(或字符串数​​组)?

这是打印的抽象语法树,但我不知道如何将其转换为字符串:

FileAST: 
  FuncDef: 
    Decl: hello, [], [], []
      FuncDecl: 
        ParamList: 
          ID: a
          ID: b
        TypeDecl: hello, []
          IdentifierType: ['int']
    Compound: 
      Return: 
        BinaryOp: +
          ID: a
          ID: b

【问题讨论】:

    标签: pycparser


    【解决方案1】:

    show 方法接受 buf 关键字参数 - 您可以在那里传递 StringIOsys.stdout 是默认值。见https://github.com/eliben/pycparser/blob/master/pycparser/c_ast.py#L30

    【讨论】:

      【解决方案2】:

      请试试这个

      from pycparser import c_parser
      src =  '''
           int hello(a, b){
              return a + b;
           }
      '''
      ast = c_parser.CParser().parse(src)
      ast_buffer_write=open("buffer.txt","w") # here will be your AST source
      ast.show(ast_buffer_write)
      ast_buffer_write.close()
      ast_buffer_read=open("buffer.txt","r")
      astString=ast_buffer_read.read()
      print(astString)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-20
        • 1970-01-01
        • 2011-04-19
        • 1970-01-01
        • 2017-07-13
        • 2018-03-20
        • 1970-01-01
        • 2022-11-18
        相关资源
        最近更新 更多