import re
def remove_empty_lines(text):
return re.sub(r'\n\s*\n', '\n', text).strip()
# 示例用法
text = """这是第一行
这是第二行
这是第三行
这是第四行"""
cleaned_text = remove_empty_lines(text)
print(cleaned_text)
-------------------------------------------------------------------------
|
上述方法中的strip()会删除行首行尾的空白字符(包括空格、制表符等),如果只想检查完全空白的行,可以使用if line.strip() != ''或if line != '\n'
如果需要保留只包含空白字符的行(非空行但只有空格/制表符),可以修改条件为if line.strip() != ''
正则表达式版本会合并多个连续空行为单个空行,如果不需要这个功能,
可以使用更简单的正则表达式:re.sub(r'^\s*$', '', text, flags=re.MULTILINE)
|
def remove_empty_lines_from_file(input_file, output_file):
with open(input_file, 'r', encoding='utf-8') as f_in:
lines = [line for line in f_in if line.strip() != '']
with open(output_file, 'w', encoding='utf-8') as f_out:
f_out.writelines(lines)
# 示例用法
remove_empty_lines_from_file('input.txt', 'output.txt')
对于大文件,逐行处理 通常更高效
-------------------------------------------------------------------------
|