数学建模社区-数学中国
标题:
删除文件注释
[打印本页]
作者:
2744557306
时间:
2024-3-31 17:15
标题:
删除文件注释
输入文件名,行注释标签,块注释标签,生成删除注释后的文件保存并覆盖原文件。
2 M. z9 X" e/ R8 @& t) Y/ x
例如C语言使用 // 和 /* */ 来注释,调用方式如下:
del_comm("main.c","//",["/*","*/"])
s: d3 V, i' z+ ?5 z1 i+ R$ R
复制代码
# 删除所有注释
5 S0 @- _% R' j* e+ p* Q& W' w
def del_comm(file:str,line_comm:str,blok_comm:list[str]):
" o# [5 A0 R( M4 C5 H: f( ]
text=""
- L5 }' A% c; ]2 |
try:
- G) A! w f, D- \5 P8 z
with open(file,encoding="utf-8") as f:
# A) b& y6 L1 } X( ?1 W- s
lines=f.readlines()
: I; n2 t9 O4 f+ _5 f
except Exception as e:
, G' H8 G( p% _9 O* S
print("decode failed",file)
& F8 ]5 U8 I; F4 K5 C
return
) ^+ K7 I! G% B. n& G
for i in range(len(lines)):
" @8 ^. t. E1 z0 Z/ R7 g0 [0 X
index=lines[i].find(line_comm)
4 M1 l, E: q/ g O L8 W( Z8 Q
if(index>=0):
8 h1 [7 F, _) e8 \ z% w% ?5 w
lstr=lines[i][:index]
+ e k7 f a, R# f3 F/ }
else:
5 r! H% b9 J& @7 r
lstr=lines[i].rstrip()
5 N3 C9 U2 e" I
if(len(lstr.strip())>0):
) l9 `( m0 z+ M: q
text+=lstr+'\n'
: |+ J5 X2 G& ?$ k4 C
elif(text[-2:]=='\\\n'):
$ B9 ]4 [$ K; i8 Y# \7 R: ?
text+='\n'
$ J5 Y; H+ @% H m6 C9 k2 V
index_start=0
# I1 N& r/ t8 H. L
text_out=""
9 ~% q6 r1 i% V2 g8 r
while True:
n1 }" c, e! o: L
index=text.find(blok_comm[0],index_start)
- E1 k$ R+ `2 u( o6 q% V8 e
index_end=text.find(blok_comm[1],index)
- r1 Q3 X' v( F. W L+ [$ l. t" I
if(index>=0 and index_end>index):
# C8 g, @1 z% _/ ?
text_out+= text[index_start:index]
; j9 H% V6 ^' L- [: i0 a# b
index_start=index_end+len(blok_comm[1])
5 o! y$ g$ u4 c2 g4 ?0 u
else:
) F2 ]$ Z/ d0 a
text_out+=text[index_start:]
# p# L$ ~# p0 y# r. S7 w
break
9 W2 e5 C, I) @" }, t
with open(file,mode="w+",encoding="utf-8") as f:
: O" p' K8 |5 M" l+ \' A8 {$ K
f.write(text_out)
# ]6 ^& b+ S ~! y* N! M4 b
: V2 H6 _5 R" X3 e( T
复制代码
" Y* A9 w4 f/ `/ T& t0 B$ J9 w
欢迎光临 数学建模社区-数学中国 (http://www.madio.net/)
Powered by Discuz! X2.5