我有一个 cpp 文件,我正在读取该文件并尝试使用 python 脚本将一行/几行添加到该 cpp 文件中。我遇到了一个问题——因为它正在读取单行注释和多行注释,所以会产生问题,因为如果我在某些字符串之后/之前写,有时它也会被添加到注释部分,这根本不应该发生。
有人可以指导我如何在使用 python 解析 cpp 文件时忽略 cpp 样式 {NOT REMOVE} 吗?
例如,我正在从后面读取一个文件并尝试添加 some text
一旦它找到两个 }
(右括号)它添加 some text
。
例如:
namespace A {
namespace B {
class C {
};
<Want to add some data here>
}
}
但是如果我有一些注释代码:
namespace A {
namespace B {
class C {
};
<Want to add some data here>
}
}
如果我有这样的评论:
namespace A {
namespace B {
class C {
};
<Want to add some data here>
}
}
// }
/*
int fun() {
}
*/
我怎样才能忽略这些评论并在从背面阅读两个 }
后添加 some text
?
注意 - 您也可以帮助我获得一些不同示例的代码。 请让我知道更多信息。
最佳答案
import re,pdb
cpat = re.compile('}')
f = open('3.txt','w')
brace = 0
newragex = re.compile(r'/\*.*\*/')
#pdb.set_trace()
for line in reversed(open("xvz.cpp").readlines()):
# if '/*' and '*/' in line.rstrip():
if re.search(newragex,line):
# print "Line is - ", line.strip()
temp = line.split('/*')
# print "Temp is - ",temp
# print "Temp[0] is - ",temp[0]
if temp[0] == None or temp[0] == ' ' or temp[0] == '':
print "Inside Single Line comment - and No Extra element is found in this line"
f.write(line.rstrip() + '\n')
continue
else:
print "INside Sinle Line comment - but There is extra non comment portion so checking pattern matching\n"
if re.search(cpat,line):
print "Pattern matched - increasing brace value\n"
brace = brace + 1
print "Brace Found - Value of Brace now - ", brace
f.write(line.rstrip() + '\n')
# if brace == 2:
# print "Two braces found"
# f.write('Testing add\n')
print line.rstrip()
# print "Single Line commment Found"
continue
if '*/' in line.rstrip():
count = count + 1
f.write(line.rstrip() + '\n')
continue
if '/*' in line.rstrip():
count = count - 1
f.write(line.rstrip() + '\n')
continue
if '//' in line.rstrip():
temp = line.split('//')
if temp[0] == None or temp[0] == ' ':
f.write(line.rstrip() + '\n')
continue
else:
if re.search(cpat,line):
print "Brace Value Before matching - ",brace
brace = brace + 1
print "Brace Found - Value of Brace now - ", brace
f.write(line.rstrip() + '\n')
if brace == 2:
print "Two braces found"
f.write('Testing add\n')
# print line.rstrip()
continue
if count == 0:
if re.search(cpat,line):
brace = brace + 1
print "Brace Found - Value of Brace now - ", brace
f.write(line.rstrip() + '\n')
print "Brace Value now -", brace
if brace == 2:
print "Two braces found"
f.write('Testing add\n')
# if brace == 2:
# print "Two braces found"
# f.write('Testing add\n')
else:
pass
f.write(line.rstrip() + '\n')
关于python - 使用python解析或读取cpp文件并通过忽略cpp文件注释添加数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40646975/