將 HTML 從站點轉換為純文本時,我們會得到很多額外的換行符。我們最多需要 1 個相鄰的換行符。這是我們正在使用的函式,但它看起來很丑陋,并且不能滿足所有用例。有沒有更 Pythonic 的方法來用更少的丑陋代碼來實作這個結果?
def clean_up_lines(message_text):
text_str = str(message_text)
text_data = text_str.replace(chr(13), "[EOL]")
text_data = text_data.replace(chr(10), "[EOL]")
text_data = text_data.replace("\n", "[EOL]")
text_data = text_data.replace("\r", "[EOL]")
for x in range(0, 10):
text_data = text_data.replace("[EOL] [EOL]", "[EOL]")
text_data = text_data.replace("[EOL] [EOL]", "[EOL]")
text_data = text_data.replace("[EOL] [EOL]", "[EOL]")
text_data = text_data.replace("[EOL] [EOL]", "[EOL]")
text_data = text_data.replace("[EOL] [EOL]", "[EOL]")
text_data = text_data.replace("[EOL] [EOL]", "[EOL]")
text_data = text_data.replace("[EOL] [EOL]", "[EOL]")
text_data = text_data.replace("[EOL][EOL]", "[EOL]")
for x in range(0, 8):
text_data = text_data.replace("[EOL][EOL]", "[EOL]")
text_data = text_data.replace("[EOL]", "\n")
return text_data
uj5u.com熱心網友回復:
如果您想要一個額外的換行符,只需使用re.sub()替換每條\nby鏈即可\n\n。\n如果您只想換行,請使用。
import re
s = 'Line1\n\n\nLine4'
print(re.sub(r'\n ', '\n\n', s))
#print(re.sub(r'\n ', '\n', s))
輸出:
Line1
Line4
uj5u.com熱心網友回復:
您可以使用正則運算式替換將多個相鄰的換行符替換為一個:
document.replace(r"\n ",r"\n")
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/335592.html
