用Python删除多余得空行

用Python删除多余的空行


有些时候文字之间的空行太多,想删除多余的空行,但是又想把全部空行删除。
如果文字之间的空行数>=2, 则保留一个空行。可以用re.sub这个行数

比如
原文段:
原文段
处理后的文段,只有一个空行:
处理后的文段,只有一个空行

示例:

#Only keep oneline, remove redundant empty lines
#Input string print:
my_string = "This is first line. \n\n\n\n\nThis is another line."
print(my_string)
text = re.sub(r'^$\n*', '\n', my_string_2, flags=re.MULTILINE)
print(text)

相关资料:
[1]:https://statisticsglobe.com/python-strip-remove-newline-from-string
[2]:https://stackoverflow.com/questions/1140958/whats-a-quick-one-liner-to-remove-empty-lines-from-a-python-string
[3]:https://docs.python.org/3/library/re.html

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在Python删除空行,你可以使用不同的方法。以下是两种常见的方法: 方法一: ```python file1 = open('text1.txt', 'r', encoding='utf-8') # 打开要去除空行的文件 file2 = open('text2.txt', 'w', encoding='utf-8') # 创建一个新文件用于存储没有空行的内容 try: for line in file1.readlines(): if line == '\n': # 如果该行是空行 line = line.strip("\n") # 去除该行的换行符 file2.write(line) # 将处理后的行写入新文件 finally: file1.close() # 关闭文件1 file2.close() # 关闭文件2 ``` 方法二: ```python mystr = 'aiyuechuang\n\n\n2021' # 要处理的字符串 print("".join([s for s in mystr.splitlines(True) if s.strip()])) # 使用列表推导式去除每行的空白字符并拼接起来 ``` 这样,你就可以使用这两种方法中的任意一种来删除Python中的空行。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [Python如何删除多余的空格与空行(有代码)](https://blog.csdn.net/lurrass/article/details/102524767)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [Python去掉文件中空行](https://blog.csdn.net/qq_33254766/article/details/114398244)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值