繁体   English   中英

Given a C++ file with many function definitions, how to get the starting and ending index of a particular function using Python?

[英]Given a C++ file with many function definitions, how to get the starting and ending index of a particular function using Python?

目的是使用 Python 用许多嵌套的{}注释整个 function void test_func test_func。

file = open(path_of_file)
data = file.readlines()
for item in data:
    if item.find('void test_func') != -1:
        point = data.index(item)
        data.insert(point, '/*')
        stack = []
        for i in data[point+1:]:
            if i.find('{') != -1:
               stack.append('{')
            elif i.find('}') != -1:
               stack.pop()
            if len(stack) == 0:
               point1= data.index(i)
               data.insert(point1+1,'*/')

使用find()方法,我可以在遍历行时找到 function 的起始索引。 我试图使用平衡括号方法,到达 function 的末尾,所以当我的堆栈为空时,我将到达test_func的末尾。

这在此示例中不起作用:

void test_func(arguments,\
arguments)
{ 

它在该行之后插入*/

/*void test_func(arguments,\
*/arguments)
{

假设“}\n”行只发生在 function 的末尾,并且总是发生在 function 的末尾,你想要这样的东西:

in_func = False
for line in file.readlines():
    line = line.strip('\r\n') # remove line breaks since print will add them
    if in_func:
        print("// " + line)
        if line == "}":
            in_func = False
    elif line.startswith('void test_func('): # paren required to not match test_func2
        print("// " + line)
        in_func = True
    else:
        print(line)

假设( / )对和{ / }对都是平衡的,您可以寻找平衡参数列表() ,然后是平衡正文第一个{}

我们要确保void test_func() {}等也被捕获,因此我已将检查提取到本地函数中,因此我们开始在同一行查找下一对字符。

file = open(path_of_file)
data = file.readlines()

start = None
params = None
body = None
open = 0
close = 0

for index, line in enumerate(data):

    def balanced(o, c):
        open += line.count(o)
        close += line.count(c)
        return open > 0 and open = close
    
    def checkBody():
        if balanced('{', '}'):
            body = index
    
    def checkParams():
        if balanced('(', ')'):
            params = index
            open = 0
            close = 0
            checkBody()
    
    def checkStart():
        if line.find('void test_func') != -1:
            start = index
            checkParams()

    if start is None:
        checkStart()
    elif params is None:
        checkParams()
    elif body is None:
        checkBody()

if start is not None and body is not None:
    data.insert(start, '/*')
    data.insert(body + 1, '*/')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM