簡體   English   中英

如何刪除 C 文件中的多行注釋以使用 Python?

[英]How can I delete multiline comments in C file to using Python?

我正在使用.readlines() 讀取 C 文件,以獲取 C 代碼文件的所有單獨行作為列表的元素。 如果任何列表元素(即 C 代碼行)是多行注釋的一部分,則需要將其替換為 ''(即刪除它但它將占用列表的相應索引),以便不會更改其他行的索引. 請檢查我的代碼以獲取詳細信息。

import re

#open and read sample.c so that code lines of sample.c are the element of list 'flist'

with open('sample.c',mode='r') as myfile: 
    flist = myfile.readlines() 


pattern1 = re.compile(r'\/{2}.*')         # to match //
pattern2 = re.compile('\/\*.*\*\/')       # to match /*......*/ in a single line or element of flist
pattern3 = re.compile('\/\*')             # to match /*
pattern4 = re.compile('\*\/')             # to match */ 

# to delete comments present in a single code line or can say in an individual element of 'flist', it's working fine.

for index,line in enumerate(flist):
    if pattern2.search(line):
       flist[index] = pattern2.sub("",line)
    if pattern1.search(line):
        flist[index] = pattern1.sub("",line)

# to delete comment starting in one line and ending in the subsequent line, **this following part is not working** 

cmnt_e = True
cmnt_s = False

for index,line in enumerate(flist):
    if pattern3.search(line) and cmnt_e == True:
        cmnt_s = True
        cmnt_e = False
    if pattern3.search(line) and cmnt_s == True:
        cmnt_e = True
        cmnt_s = False
    if cmnt_s == True and cmnt_e == False:
        flist[index] = ''

我並沒有看太多細節,但是您正在使用 pattern3 來開始和結束評論。 我想它應該是這樣的

    if pattern3.search(line) and cmnt_e == True:
        cmnt_s = True
        cmnt_e = False
    if pattern4.search(line) and cmnt_s == True:
        cmnt_e = True
        cmnt_s = False

我也會警惕像這樣的奇怪模式(是的,我有時將它用於實驗性的東西,你只需翻轉第一個斜線來翻轉活動代碼):

//*
ACTIVE_CODE
/*/
INACTIVE_CODE
//*/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM