数学建模社区-数学中国

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

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