這是一個字串。我想用評論本身洗掉 C 風格的評論。不使用正則運算式
a = "word234 /*12aaa12*/"
我希望輸出只是:
word234
uj5u.com熱心網友回復:
這是一個簡單的演算法,將狀態保持在 2 個字符以上,并使用標志來保持或不保持字符。
a = "word234 /*12aaa12*/ word123 /*xx*xx*/ end"
out = []
add = True
prev = None
for c in a:
if c == '*' and prev == '/':
if add:
del out[-1]
add = False
if c == '/' and prev == '*':
add = True
prev = c
continue
prev = c
if add:
out.append(c)
s2 = ''.join(out)
print(s2)
輸出:
word234 word123 end
如果您想處理嵌套注釋(不確定這是否存在,但這很有趣),該演算法很容易修改為使用計算深度級別的標志:
a = "word234 /*12aaa12*/ word123 /*xx/*yy*/xx*/ end"
out = []
lvl = 0
prev = None
for c in a:
if c == '*' and prev == '/':
if lvl == 0:
del out[-1]
lvl -= 1
if c == '/' and prev == '*':
lvl = 1
prev = c
continue
prev = c
if lvl == 0:
out.append(c)
s2 = ''.join(out)
print(s2)
uj5u.com熱心網友回復:
您可以使用它str.find來搜索字串中出現的/*和*/。
str.find/*回傳和的索引*/。如果在字串中找不到,則str.find回傳。我們可以將其用作回圈中的停止條件,搜索下一條評論,直到沒有更多評論為止。-1/*
然后,我們可以使用這些索引str.join將所有非注釋子字串連接到一個字串中。
def indices_c_comments(s):
yield 0
i = s.find('/*')
while i != -1:
j = s.find('*/', i)
yield from (i, j 2)
i = s.find('/*', j)
yield len(s)
def strip_c_comments(s):
g = indices_c_comments(s)
return ''.join(s[i:j] for i,j in zip(g, g))
for s in ('text/*comment*/text/*comment*/text', 'text/*comment*//*comment*/text', 'text/*comment*/', '/*comment*/'):
print('"{}" --> "{}"'.format(s, strip_c_comments(s)))
# "text/*comment*/text/*comment*/text" --> "texttexttext"
# "text/*comment*//*comment*/text" --> "texttext"
# "text/*comment*/" --> "text"
# "/*comment*/" --> ""
uj5u.com熱心網友回復:
加強@mozway 提出的答案:
(出于演示目的,條件比必要的更明確。)
def remove_comments(s, start_tok='/*', end_tok='*/', nested=True, raise_on_imbalance=True):
lvl = 0
output = ""
i = 0
while i < len(s):
start_len_chs = s[i:i len(start_tok)]
end_len_chs = s[i:i len(end_tok)]
if start_len_chs == start_tok and nested:
lvl = 1
i = len(start_tok)
elif start_len_chs == start_tok and not nested and lvl == 0:
lvl = 1
i = len(start_tok)
elif start_len_chs == start_tok and not nested and lvl != 0:
output = start_len_chs
i = len(start_tok)
elif end_len_chs == end_tok and nested:
lvl -= 1
i = len(end_tok)
elif end_len_chs == end_tok and not nested and lvl != 0:
lvl = 0
i = len(end_tok)
elif end_len_chs == end_tok and not nested and lvl == 0:
output = end_len_chs
i = len(end_tok)
elif lvl == 0:
output = s[i]
i = 1
else:
i = 1
if raise_on_imbalance and (start_tok in output or end_tok in output):
raise ValueError("Imbalanced comment tokens")
return output
你真的應該嘗試自己做這件事。如果您不了解提供的答案中發生了什么,那么您將一無所獲。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/472650.html
下一篇:Matlab矩陣到單元格
