python - PYTHON 基本文本浏览器/刮板。如何删除空行但在段落之间至少保留一个
问题描述
我创建了一个基本的文本浏览器/抓取工具,可以满足我的要求。但是,当收到来自站点的文本时,会有很多额外的空白行。有没有办法删除多余的空行但在段落之间至少保留一个空行?
这是我的代码....
import urllib.request
from urllib.request import urlopen
from bs4 import BeautifulSoup
url = input('Enter a URL starting with https or http: ')
host = url
webUrl = urllib.request.urlopen(host)
print('result code: ' + str(webUrl.getcode()))
data = webUrl.read()
soup = BeautifulSoup(data, features="html.parser")
for script in soup(["script", "style"]):
script.extract()
text = soup.get_text()
print (text)
input('Scroll Up or Press ENTER to Exit')
解决方案
使用re.sub
单个换行符替换多个换行符,在它们之间和之前使用可选的空格:
import re
text = re.sub(r"\s*\n", "\n", text)
推荐阅读
- python - 使用省略号重塑 numpy 数组的问题
- c# - 有没有办法只在 Z 轴 Unity2d 上旋转
- angular - 带有两个 *ngIf 和一个 else 的条件
- c++ - 编译器不正确地将文件包含在同一目录中
- sql - 在 SQL Query 期间编辑数据而不事先编辑表
- c++ - 线程本地存储,thread_local关键字是必须的吗?
- javascript - 如何将 Rails 控制器值分配给 JavaScript 常量
- python-3.x - 模式包安装失败
- mysql - MySQL:可能的变量生命周期问题,可能的范围问题,老实说不确定
- pandas - 如何创建自己的自定义转换器并在 scikit-learn 的管道中使用它们?