数学建模社区-数学中国
标题:
删除文件注释
[打印本页]
作者:
2744557306
时间:
2024-3-31 17:15
标题:
删除文件注释
输入文件名,行注释标签,块注释标签,生成删除注释后的文件保存并覆盖原文件。
+ y) O( o) O2 m3 O1 e+ k8 {3 `' p' a
例如C语言使用 // 和 /* */ 来注释,调用方式如下:
del_comm("main.c","//",["/*","*/"])
/ M, D7 b, P$ ~% Y
复制代码
# 删除所有注释
7 u% |. i0 _0 w: r4 _0 e" r5 k
def del_comm(file:str,line_comm:str,blok_comm:list[str]):
8 D" x% _) f! q, ?7 d
text=""
+ Z' g/ `8 N6 X* E
try:
) g/ ~2 }! `& ?; a3 V5 g
with open(file,encoding="utf-8") as f:
! z; T7 l- `# p( V/ Y; }- ~
lines=f.readlines()
* Z, V, w$ q1 w
except Exception as e:
% Z1 ?" y- @' Y' {' ^% v M
print("decode failed",file)
8 _/ r9 j$ K/ C" g+ t5 O0 U5 B
return
' `# W& C( d( G; K
for i in range(len(lines)):
9 ^. U- z" i _0 B/ K- t
index=lines[i].find(line_comm)
' m+ ?3 P$ i( U4 \, k3 k G8 f
if(index>=0):
- O( h& C4 ^6 q0 E
lstr=lines[i][:index]
3 |+ C* V; {$ Z* F' e9 X. h$ R
else:
) y: i5 j2 n5 J
lstr=lines[i].rstrip()
1 x$ U) \& h. Y7 ~. B
if(len(lstr.strip())>0):
4 t. v; ^* E) f. b5 I
text+=lstr+'\n'
$ \: y: ~) l6 f# e
elif(text[-2:]=='\\\n'):
7 v4 [* p/ Q4 `* ~( q7 a
text+='\n'
4 {2 [+ Z& _5 K9 F2 t/ f+ G+ f. m
index_start=0
$ V$ i6 ?, E! J- W; `
text_out=""
# s. ~# E# g$ c( ~9 H" ~ g. [; v
while True:
9 V$ W$ S' d/ Y8 k$ o2 x
index=text.find(blok_comm[0],index_start)
7 b& K( v0 ^( ~! C
index_end=text.find(blok_comm[1],index)
$ ~3 n/ n3 A8 r/ L
if(index>=0 and index_end>index):
! U9 N5 ^6 e/ a: V8 v
text_out+= text[index_start:index]
! m% Y; P$ s# |6 S% f6 q- n) z
index_start=index_end+len(blok_comm[1])
/ D, r% e/ a8 y- y' C
else:
0 F, a4 \$ b+ T- R) W
text_out+=text[index_start:]
& b5 T7 g, { K4 H, |
break
) C/ t$ b+ }* I: [! W' r) @
with open(file,mode="w+",encoding="utf-8") as f:
' X% m# Q1 e$ K
f.write(text_out)
5 V- V% e; o2 q3 K0 H
4 X( h% H$ M2 ?3 s" l
复制代码
0 q& r3 x: \2 R. o
欢迎光临 数学建模社区-数学中国 (http://www.madio.net/)
Powered by Discuz! X2.5