首页 > 解决方案 > 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')

标签: python

解决方案


使用re.sub单个换行符替换多个换行符,在它们之间和之前使用可选的空格:

import re
text = re.sub(r"\s*\n", "\n", text)

推荐阅读