数学建模社区-数学中国
标题:
删除文件注释
[打印本页]
作者:
2744557306
时间:
2024-3-31 17:15
标题:
删除文件注释
输入文件名,行注释标签,块注释标签,生成删除注释后的文件保存并覆盖原文件。
, w2 s8 h" |! e6 c( {
例如C语言使用 // 和 /* */ 来注释,调用方式如下:
del_comm("main.c","//",["/*","*/"])
9 ?1 V o: x2 @
复制代码
# 删除所有注释
- h" Y6 R; h0 a. u8 a1 Q' ~
def del_comm(file:str,line_comm:str,blok_comm:list[str]):
+ [, G- k" h' w, U( u8 K# x1 a
text=""
/ E9 C8 }7 Z2 r' W# Z) j8 s
try:
l6 {' E8 m; p" [) E
with open(file,encoding="utf-8") as f:
5 ~: a6 y- K' w; b
lines=f.readlines()
- \) p0 v+ S" x y: W; V# f6 X' {
except Exception as e:
& Z/ \$ W5 g4 ?) x9 A, l
print("decode failed",file)
* C! K- t) s5 I T
return
# x: E+ f' s/ n6 H. G- @
for i in range(len(lines)):
0 F: \7 S# k4 N1 ^2 D# f
index=lines[i].find(line_comm)
' X9 p+ l: i9 W" v1 A0 N1 X i$ }- n
if(index>=0):
0 D" G1 J) b" U/ X3 H7 d& n
lstr=lines[i][:index]
3 P$ i1 x! ]$ L" I" V3 p$ D0 I P
else:
9 u- u5 [ N% |% A
lstr=lines[i].rstrip()
5 L. E; E; Q" `4 a5 ^
if(len(lstr.strip())>0):
( h4 G- Z1 Q6 }% ^& z( {
text+=lstr+'\n'
) H2 O2 C& x C
elif(text[-2:]=='\\\n'):
+ J! _5 b. Y# t& G2 d) e' ]# K, V
text+='\n'
3 U5 M. X j. c) L# E5 O4 h( E8 _
index_start=0
; A3 }2 ^# M5 O! B8 |
text_out=""
0 C2 P0 |7 |. g, \8 ~% _
while True:
" H9 Q6 x8 _, n% O3 P
index=text.find(blok_comm[0],index_start)
# Z8 i6 t# E" G6 c/ @2 j
index_end=text.find(blok_comm[1],index)
, N3 @8 T2 |6 ^$ }5 A
if(index>=0 and index_end>index):
' |$ m# C! W% h( R+ I
text_out+= text[index_start:index]
b. o9 g+ j% T: a
index_start=index_end+len(blok_comm[1])
9 {0 S5 Z' c) G9 m
else:
O- U2 F! X; }& {" J( K
text_out+=text[index_start:]
! G+ P- l8 i/ W% t. c. Z
break
: }" t6 S8 @7 C" Y0 [
with open(file,mode="w+",encoding="utf-8") as f:
7 y0 t0 g& y e
f.write(text_out)
$ z. o( Z+ l" J1 ^" c
0 |! a6 f& U7 v) r* ]: i
复制代码
# n4 k4 Q: a' F( @& b9 O' v
欢迎光临 数学建模社区-数学中国 (http://www.madio.net/)
Powered by Discuz! X2.5