我正在从许多来源分析文本数据,无论行结尾是 r n还是 n,我都需要删除空白行,但是下面的丑陋方法是我发现在它们之间使用空间清理线路端的唯一方法。这是我使用的代码。而且我知道这不是做到这一点的最佳方法,但是到目前为止,我已经与Regex脱颖而出。最好的方法是什么?
text = text.replace('r', '[EOL]')
text = text.replace('n', '[EOL]')
for x in range(0, 30):
text = text.replace("[EOL] [EOL]", "[EOL]")
text = text.replace("[EOL] [EOL]", "[EOL]")
text = text.replace("[EOL] [EOL]", "[EOL]")
text = text.replace("[EOL] [EOL]", "[EOL]")
text = text.replace("[EOL] [EOL]", "[EOL]")
text = text.replace("[EOL] [EOL]", "[EOL]")
text = text.replace("[EOL] [EOL]", "[EOL]")
text = text.replace("[EOL] [EOL]", "[EOL]")
text = text.replace("[EOL][EOL]", "[EOL]")
text = text.replace("[EOL]", "rn")
您需要使用re.sub
re.sub(r'[rn]+[ t]*[rn]*', r'n', text)
对于'空白'行定义为任何看不到文本的行,尝试
查找(?m)$s+^
替换rn