我有一个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
后忽略这些评论并添加}
?
注意 - 您也可以帮助我使用不同的示例获取一些代码。 如需更多信息,请通知我。
答案 0 :(得分:-1)
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')