QQ登录

只需要一步,快速开始

 注册地址  找回密码
查看: 2226|回复: 0
打印 上一主题 下一主题

删除文件注释

[复制链接]
字体大小: 正常 放大

1189

主题

4

听众

2934

积分

该用户从未签到

跳转到指定楼层
1#
发表于 2024-3-31 17:15 |只看该作者 |正序浏览
|招呼Ta 关注Ta
输入文件名,行注释标签,块注释标签,生成删除注释后的文件保存并覆盖原文件。
; f# Y& ]7 n) g1 X6 h6 h例如C语言使用 // 和 /* */ 来注释,调用方式如下:
  1. del_comm("main.c","//",["/*","*/"])
    0 V+ l0 \: [# a0 Y6 N* O- D
复制代码
  1. # 删除所有注释
    # x; e# K. A$ I2 Q  S
  2. def del_comm(file:str,line_comm:str,blok_comm:list[str]):0 d( V; H2 y3 T) J# Z
  3.     text=""
    6 _% F. |# F) ~
  4.     try:
    ( J: J' W& i\" G0 D
  5.         with open(file,encoding="utf-8") as f:
    4 D5 V) [& M! d1 m
  6.             lines=f.readlines()
    1 v; V; T- f+ t\" ?- A0 t
  7.     except Exception as e:( \& f! B5 w: I0 e0 l
  8.         print("decode failed",file)( M7 |. V' B$ V\" g3 q
  9.         return
    ( [( T4 r\" S9 h, Q$ i% r
  10.     for i in range(len(lines)):
    ! r2 N2 T; d* a( [0 a
  11.         index=lines[i].find(line_comm)' N! ^( P7 `. m3 z1 W
  12.         if(index>=0):
    ) ^4 Z3 Y9 M0 }) [8 @
  13.             lstr=lines[i][:index]
    / |& z9 @( M' E, G' T; `
  14.         else:
    . u0 d5 u( s0 I6 d\" H8 x
  15.             lstr=lines[i].rstrip()
    . D! j8 v4 F$ {8 C9 f' v
  16.         if(len(lstr.strip())>0):# ]  _1 ?9 r8 N
  17.             text+=lstr+'\n') X8 f9 _1 j1 X
  18.         elif(text[-2:]=='\\\n'):
    3 u- |4 ~& `1 W  e% i8 u! x8 x
  19.             text+='\n'* X# R! P0 k+ s\" j4 k
  20.     index_start=0
    7 W/ ]$ S0 d2 V  b7 ?1 l
  21.     text_out=""' L8 [* W- ]  d& v
  22.     while True:
    / Q) w, s* B8 z
  23.         index=text.find(blok_comm[0],index_start)
    8 E\" Q5 u9 c' I' Q. f) G* P
  24.         index_end=text.find(blok_comm[1],index)
    1 m0 G) o- x! ~) ?$ [0 ~
  25.         if(index>=0 and index_end>index):
    / l+ P& @9 |+ q, w0 P/ l/ l
  26.             text_out+= text[index_start:index]
    5 Z8 Q5 G6 Y& ~6 A3 A. u, m* y
  27.             index_start=index_end+len(blok_comm[1])
    # d+ ^) r2 G# O# r% |5 E) N1 g1 f
  28.         else:
    % y9 g; N* ?) I: Q6 t
  29.             text_out+=text[index_start:]! s, c1 n3 h- n& d2 A
  30.             break
    % o' F, c+ ^( _2 S1 D
  31.     with open(file,mode="w+",encoding="utf-8") as f:
    ) Q  \) p! H: i. H! a5 O1 C' P
  32.         f.write(text_out)- Y3 q( _% D0 k9 ~8 n2 \
  33.         
    . x4 d; M\" B: u3 w8 i, ?* @
复制代码

" q2 V" @9 Q2 V) h+ `4 [- G
zan
转播转播0 分享淘帖0 分享分享0 收藏收藏0 支持支持0 反对反对0 微信微信
您需要登录后才可以回帖 登录 | 注册地址

qq
收缩
  • 电话咨询

  • 04714969085
fastpost

关于我们| 联系我们| 诚征英才| 对外合作| 产品服务| QQ

手机版|Archiver| |繁體中文 手机客户端  

蒙公网安备 15010502000194号

Powered by Discuz! X2.5   © 2001-2013 数学建模网-数学中国 ( 蒙ICP备14002410号-3 蒙BBS备-0002号 )     论坛法律顾问:王兆丰

GMT+8, 2026-7-18 16:02 , Processed in 0.433840 second(s), 52 queries .

回顶部