我在一個文本檔案中有多個 Fortran 子例程實體,如下所示:
SUBROUTINE ABCDEF(STRING1)
STRING2
STRING3
.
.
.
STRINGN
END
如何使用正則運算式在 python 中洗掉子程式及其內容?
我已經嘗試過這段代碼但沒有成功:
with open(input, 'r') as file:
output = open(stripped, 'w')
try:
for line in file:
result = re.sub(r"(?s)SUBROUTINE [A-Z]{6}(.*?)\bEND\b", input)
output.write("\n")
finally:
output.close()
uj5u.com熱心網友回復:
這行得通嗎?我用 input_file 替換了 input ,因為 input 是一個內置函式,所以使用它是不好的做法。
pattern = r"(?s)SUBROUTINE [A-Z]{6}(.*?)\bEND\b"
regex = re.compile(pattern, re.MULTILINE|re.DOTALL)
with open(input_file, 'r') as file:
with open(stripped, 'w') as output_file:
result = regex.sub('', file.read())
output_file.write(result)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/358677.html
