QQ登录

只需要一步,快速开始

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

删除文件注释

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

1189

主题

4

听众

2934

积分

该用户从未签到

跳转到指定楼层
1#
发表于 2024-3-31 17:15 |只看该作者 |倒序浏览
|招呼Ta 关注Ta
输入文件名,行注释标签,块注释标签,生成删除注释后的文件保存并覆盖原文件。! q+ b* l8 h4 j
例如C语言使用 // 和 /* */ 来注释,调用方式如下:
  1. del_comm("main.c","//",["/*","*/"])  o& B2 m' b4 O8 J3 U5 H. J$ R
复制代码
  1. # 删除所有注释
    ! {2 }2 A: f4 Z( m% g* s
  2. def del_comm(file:str,line_comm:str,blok_comm:list[str]):
    ) x2 W! p# ~0 R6 u
  3.     text=""
    & Y. s+ o/ Y1 }1 ?  O! l$ q: U- G
  4.     try:: @# W9 W% k8 ~; |; L
  5.         with open(file,encoding="utf-8") as f:
    4 M1 Z& a! Z\" H# B7 J7 \2 r
  6.             lines=f.readlines()
    0 u3 t7 C$ S) _% k
  7.     except Exception as e:
    8 z5 b7 D- Q& Y\" x3 I) ]; k8 n4 `
  8.         print("decode failed",file)
    ! g/ x1 `4 \; M
  9.         return
    . \) t8 t. R# u* x
  10.     for i in range(len(lines)):* `! c( `2 p# g2 |. D$ v
  11.         index=lines[i].find(line_comm)
    , t, n: B& a# a4 D' V
  12.         if(index>=0):
    1 ~# n$ z0 ]5 `5 ~- C
  13.             lstr=lines[i][:index]
    , N( E8 x9 B$ x! e4 q0 T* U, N
  14.         else:\" R: d) Q! ^/ [, x6 {
  15.             lstr=lines[i].rstrip()
    6 n2 b. j2 Y6 o: Q/ x
  16.         if(len(lstr.strip())>0):6 M# F! M3 x: K6 R7 b$ r
  17.             text+=lstr+'\n'' Q8 @& Z/ i0 P  V, z& J+ W
  18.         elif(text[-2:]=='\\\n'):
    , h0 h& [# e  U# f, M' s* X! V
  19.             text+='\n'0 _1 [/ g3 k$ t- _: {8 ?4 L
  20.     index_start=0
    / r4 N) G. ?; e; @
  21.     text_out=""# N6 t5 \  F- F+ y8 r
  22.     while True:4 _5 g; Q& }3 p; e! o1 g
  23.         index=text.find(blok_comm[0],index_start)
    \" e8 k2 e- i4 t4 _\" e) T
  24.         index_end=text.find(blok_comm[1],index)* ?4 n2 L) P) ]& U
  25.         if(index>=0 and index_end>index):
    + h, i* F\" m. E% K
  26.             text_out+= text[index_start:index]
    . c; [4 X* R0 Q\" G
  27.             index_start=index_end+len(blok_comm[1])* {. A- W9 Q+ i3 i
  28.         else:. N4 \$ S( `# E
  29.             text_out+=text[index_start:]
    - k5 }' _2 ?  R\" ^\" i
  30.             break+ X\" ]* H8 r2 R\" B5 F9 o3 W
  31.     with open(file,mode="w+",encoding="utf-8") as f:
    : s, }8 ~9 y) E
  32.         f.write(text_out)$ n$ B4 ~3 Z. w2 q* p. q
  33.         
    ! O* t) @% v0 |. x5 C4 i# B
复制代码
( l) g& j# h- O, U8 ~" C
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 09:55 , Processed in 0.408279 second(s), 51 queries .

回顶部