[英]Removing the texts within a comment block ?* */ in python
我的輸入文件test.sas
文件如下所示:
My
Name is Joe
How are you?;
/* Comment 1 */
/*Comment 2
blah blah
blah blah blah
blah blah blah blah;*/
/* Comment 3 */
I am great
當我使用以下代碼時,得到的結果恰好在代碼之后:
writing = True
with open('test.sas', 'r') as file:
with open('output.sas','w') as out:
for line in file:
if writing:
if '/*' in line:
writing = False
else:
out.write(line)
elif '*/' in line:
writing = True
結果:
My
Name is Joe
How are you?;
但我想得到以下結果:
My
Name is Joe
How are you?;
I am great
我不知道自己在做什么錯。 基本上,我想刪除注釋塊中的文本,並將其余部分寫到輸出文件中。
更改最終
elif '*/' in line:
writing = True
至
if '*/' in line:
writing = True
這樣,如果兩個語句都在同一行上,那么您就可以命中它們。
我在每行末尾添加了一些注釋,以顯示您的writing
變量的狀態。
My //True
Name is Joe //True
How are you?; //True
/* Comment 1 */ //False
/*Comment 2 //False
blah blah //False
blah blah blah //False
blah blah blah blah;*/ //True
/* Comment 3 */ //False
I am great //False
您知道問題出在哪里嗎? 由於if語句每行只能評估一次(每個循環一次),因此不會在同時具有/*
和*/
行之后將writing
設置為True
。
要在一行上檢查兩個注釋符號,請允許兩個if語句在一個循環中工作。 elif '*/' in line:
更改elif '*/' in line:
末尾的if '*/' in line
。 這樣, 即使最初將寫入設置為False ,它也可以設置為在每個循環結束時寫入!
re.sub()方法用於用其他東西“替換匹配項”
re.sub(樣式,替換項,字符串)
模式:(/ * [\\ s \\ S \\ w \\ W] ** / \\ r?\\ n?)-捕捉引號之間的所有內容,然后跟着返回或換行符
import re
with open('text.sas') as f:
string = f.read()
pattern = r'(/\*[\s\S\w\W]*\*/\r?\n?)'
new_string = re.sub(pattern, '', string)
print(new_string)
""" Output:
My
Name is Joe
How are you?;
I am great
"""
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.