给定一个C++具有许多功能定义的文件,如何使用Python获取特定函数的启动和结束索引?
目的是使用python对整个函数void 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()
方法,我可以在迭代行时找到该功能的起始索引。我试图使用平衡的括号方法来达到函数的末尾,因此,当我的堆栈为空时,我将到达test_func
的末尾。
在此示例中,这不起作用:
void test_func(arguments,\
arguments)
{
它在行之后插入*/
:
/*void test_func(arguments,\
*/arguments)
{
The purpose is to comment the entire function void test_func
with many nested {}
using Python.
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,'*/')
Using the find()
method I can find the starting index of the function while iterating over the lines. I was trying to use the balanced parenthesis method, to reach the end of the function, So when my stack is empty I will reach the end of the test_func
.
This is not working in this example:
void test_func(arguments,\
arguments)
{
It is inserting */
just after the line:
/*void test_func(arguments,\
*/arguments)
{
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设“} \ n”行仅发生在函数的末尾,并且总是在函数结束时发生,则需要类似的东西:
Assuming that a "}\n" line only happens at the end of a function and always happens at the end of a function, you want something like:
假设两个
(
/)
对和{
/}
对配对,您可以查找)
平衡参数列表的(
,然后}
平衡了身体的第一个{
。我们要确保<代码> void还捕获了Test_func(){} 等,因此我将支票删除到本地功能中,因此我们开始在同一条线上查看下一对字符。
Assuming that both
(
/)
pairs and{
/}
pairs are balanced, you can look for the)
that balances the parameter list's(
and then the}
that balances the body's first{
.We want to ensure that
void test_func() {}
etc is also caught, so I've pulled out the checks into local functions, so we start looking on the same line for the next pair of characters.