簡體   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