数学建模社区-数学中国

标题: 删除文件注释 [打印本页]

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





欢迎光临 数学建模社区-数学中国 (http://www.madio.net/) Powered by Discuz! X2.5