数学建模社区-数学中国

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

作者: 2744557306    时间: 2024-3-31 17:15
标题: 删除文件注释
输入文件名,行注释标签,块注释标签,生成删除注释后的文件保存并覆盖原文件。
, w2 s8 h" |! e6 c( {例如C语言使用 // 和 /* */ 来注释,调用方式如下:
  1. del_comm("main.c","//",["/*","*/"])9 ?1 V  o: x2 @
复制代码
  1. # 删除所有注释
    - h" Y6 R; h0 a. u8 a1 Q' ~
  2. def del_comm(file:str,line_comm:str,blok_comm:list[str]):
    + [, G- k" h' w, U( u8 K# x1 a
  3.     text=""/ E9 C8 }7 Z2 r' W# Z) j8 s
  4.     try:
      l6 {' E8 m; p" [) E
  5.         with open(file,encoding="utf-8") as f:
    5 ~: a6 y- K' w; b
  6.             lines=f.readlines()- \) p0 v+ S" x  y: W; V# f6 X' {
  7.     except Exception as e:& Z/ \$ W5 g4 ?) x9 A, l
  8.         print("decode failed",file)* C! K- t) s5 I  T
  9.         return# x: E+ f' s/ n6 H. G- @
  10.     for i in range(len(lines)):
    0 F: \7 S# k4 N1 ^2 D# f
  11.         index=lines[i].find(line_comm)' X9 p+ l: i9 W" v1 A0 N1 X  i$ }- n
  12.         if(index>=0):
    0 D" G1 J) b" U/ X3 H7 d& n
  13.             lstr=lines[i][:index]
    3 P$ i1 x! ]$ L" I" V3 p$ D0 I  P
  14.         else:
    9 u- u5 [  N% |% A
  15.             lstr=lines[i].rstrip()5 L. E; E; Q" `4 a5 ^
  16.         if(len(lstr.strip())>0):
    ( h4 G- Z1 Q6 }% ^& z( {
  17.             text+=lstr+'\n'
    ) H2 O2 C& x  C
  18.         elif(text[-2:]=='\\\n'):+ J! _5 b. Y# t& G2 d) e' ]# K, V
  19.             text+='\n'
    3 U5 M. X  j. c) L# E5 O4 h( E8 _
  20.     index_start=0
    ; A3 }2 ^# M5 O! B8 |
  21.     text_out=""0 C2 P0 |7 |. g, \8 ~% _
  22.     while True:
    " H9 Q6 x8 _, n% O3 P
  23.         index=text.find(blok_comm[0],index_start)
    # Z8 i6 t# E" G6 c/ @2 j
  24.         index_end=text.find(blok_comm[1],index), N3 @8 T2 |6 ^$ }5 A
  25.         if(index>=0 and index_end>index):' |$ m# C! W% h( R+ I
  26.             text_out+= text[index_start:index]
      b. o9 g+ j% T: a
  27.             index_start=index_end+len(blok_comm[1])
    9 {0 S5 Z' c) G9 m
  28.         else:  O- U2 F! X; }& {" J( K
  29.             text_out+=text[index_start:]
    ! G+ P- l8 i/ W% t. c. Z
  30.             break
    : }" t6 S8 @7 C" Y0 [
  31.     with open(file,mode="w+",encoding="utf-8") as f:
    7 y0 t0 g& y  e
  32.         f.write(text_out)
    $ z. o( Z+ l" J1 ^" c
  33.         
    0 |! a6 f& U7 v) r* ]: i
复制代码

# n4 k4 Q: a' F( @& b9 O' v




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