数学建模社区-数学中国

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

作者: 2744557306    时间: 2024-3-31 17:15
标题: 删除文件注释
输入文件名,行注释标签,块注释标签,生成删除注释后的文件保存并覆盖原文件。
/ _" }" r  `! R  b! [% ~7 z0 O6 T4 U例如C语言使用 // 和 /* */ 来注释,调用方式如下:
  1. del_comm("main.c","//",["/*","*/"])" K! X4 Y* Q( _/ G
复制代码
  1. # 删除所有注释
    , \" ^- ?+ j/ s5 @. d* \: k
  2. def del_comm(file:str,line_comm:str,blok_comm:list[str]):
    ; l9 M3 u$ [- K9 Y& z' k* D
  3.     text=""
    1 E/ ?( G+ P& b
  4.     try:/ R2 i. _6 P+ u% C' h
  5.         with open(file,encoding="utf-8") as f:
    , v, m. G& R7 j4 F& h! C
  6.             lines=f.readlines()
    5 {: f3 u4 }1 \& s' {. @/ h
  7.     except Exception as e:+ S8 y) w+ }. A) f
  8.         print("decode failed",file)# b- {- q; F2 Z) s: J0 F- Q
  9.         return' {' c  M& a, @( _
  10.     for i in range(len(lines)):) h' K! i  q- _4 T" D) b5 Y* v9 V
  11.         index=lines[i].find(line_comm)) g- T4 [. T" R
  12.         if(index>=0):
    6 L! v' b3 {1 P% _" a
  13.             lstr=lines[i][:index]$ ^9 L1 z% f$ N' B
  14.         else:
    . D2 C- {6 h6 ~! v! v7 v3 a: n
  15.             lstr=lines[i].rstrip()7 A3 B0 ^' J2 h: Z3 ^7 a
  16.         if(len(lstr.strip())>0):
    # q  a8 b" z8 ?$ {. H, F" t* X
  17.             text+=lstr+'\n'
    2 k' ^% I( d* n) v# ~# k
  18.         elif(text[-2:]=='\\\n'):# x3 {5 P- T+ K+ j$ S: j  K
  19.             text+='\n'  @0 J  `" u: d$ c0 x; t5 r7 N! ]
  20.     index_start=04 q! @0 r7 f% c% m% U, I  J9 }
  21.     text_out=""5 }, O4 ~) `$ R5 I+ ]* {
  22.     while True:+ b; N2 Y- |, @1 e* }$ {% W
  23.         index=text.find(blok_comm[0],index_start)
    8 p: B! f# A7 J  w2 t5 n
  24.         index_end=text.find(blok_comm[1],index)% T# N& r9 M$ ^2 H4 y
  25.         if(index>=0 and index_end>index):
    : j# d# H1 ?1 ^. @; g( ^
  26.             text_out+= text[index_start:index]
    % w; n+ t! k! }1 N  z# c9 B- R3 g
  27.             index_start=index_end+len(blok_comm[1])# c7 a1 M+ S0 N0 ~  X5 F
  28.         else:3 P8 D; D* Y8 K- X
  29.             text_out+=text[index_start:]! [$ p6 X/ ^1 u* u
  30.             break
    8 |) D  b$ e7 a; W% E7 J
  31.     with open(file,mode="w+",encoding="utf-8") as f:
    # R/ |& d* x6 K$ z( {3 {
  32.         f.write(text_out)1 R! b  K* ?6 a7 }7 ^
  33.         
      P% p! x+ z; A' K
复制代码

. k6 l3 b+ O( l+ {  _# v0 X




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