【发布时间】:2020-08-08 04:55:10
【问题描述】:
从各个网站抓取文本后,我想规范化这段文本以便分析它。我想做的一个步骤是用一个空格替换多个空格。
我知道 Stack Overflow 上经常讨论这个话题。但是,使用常见的方式,例如:
string = ' '.join(string.split())
或
string = re.sub(' +', ' ', string)
似乎不会为每个网页产生预期的结果。请在下面找到我使用的代码摘录和美国证券交易委员会文件的示例,我无法做到没有多个空格。
import re
from selenium import webdriver
link = r"https://www.sec.gov/Archives/edgar/data/1800/000104746919001316/a2237648zdef14a.htm"
driver = webdriver.Chrome('./chromedriver')
driver.get(link)
x = driver.page_source
#Function to clean
def cleanhtml(raw_html):
cleanr = re.compile('<.*?>')
cleantext = re.sub(cleanr, '', raw_html)
return cleantext
#Cleaning
x = str(x).replace('<', ' <')
x = cleanhtml(x)
x = x.replace('<br>', ' ').replace(' ', ' ').replace('&', '&').replace('/\s\s+/g',' ').replace('•', ' ').replace("<", " ").replace("_", " ").replace("●", " ")
x = ' '.join(x.split())
#Results with persist to have multiple white spaces :-(
print(x)
注意:我刚刚编辑了我的问题,因为我之前的示例不合适!感谢您到目前为止的回答!
【问题讨论】:
-
white space != spacebar ... \t 或 \n 等也是空格。你是什么意思?你的正则表达式 f.e.只消除连续的 空格键 东西...
-
你试过
re.sub('\s+', ' ', string)(@PatrickArtner 的评论)吗? -
是否还有其他代码可以删除 标记和 HTML 元素?输入和预期输出到底是什么?
-
@MichaelMü 你能举一个你试图清理的 actual 字符串值的例子吗?给出的示例包含 html 标签(例如 cmets)。另外,如果您使用的是 html 解析器,我想我已经为您处理 ...
-
...您没有使用 html 解析器(而不是使用正则表达式)是否有特殊原因?
标签: python web-scraping removing-whitespace