2017-10-10 220 views
0

我有一个名为BBC_news_home.html的文件,我需要删除所有标记标记,所以我留下的只是一些文本。到目前为止,我有:Python - 删除标记标签并从文件中读取html?

def clean_html(html): 
    cleaned = '' 

line = html 

pattern = r'(<.*?>)' 

result = re.findall(pattern, line, re.S) 

if result: 
    f = codecs.open("BBC_news_home.html", 'r', 'utf-8') 
    print(f.read()) 
else: 
    print('Not cleaned.') 
return cleaned 

我与regex101.com检查的模式是正确的我只是不知道如何打印输出,以检查是否标记标签都没有了?

+0

您可能想查看[BeautifulSoup](https://www.crummy.com/software/BeautifulSoup/bs4/doc/),更具体地说[.get_text()](https://www.crummy。 COM /软件/ BeautifulSoup/BS4/DOC /#获取文本)。 –

回答

0

你真的应该使用BeautifulSoup这个。根据你需要的python版本做pip3 install BeautifulSoup4pip install BeautifulSoup4。我已经发布了对类似问题here的回答。为完整起见:

from bs4 import BeautifulSoup 

def cleanme(html): 
    soup = BeautifulSoup(html) # create a new bs4 object from the html data loaded 
    for script in soup(["script"]): 
     script.extract() 
    text = soup.get_text() 
    return text 
testhtml = "<!DOCTYPE HTML>\n<head>\n<title>THIS IS AN EXAMPLE </title><style>.call {font-family:Arial;}</style><script>getit</script><body>I need this text captured<h1>And this</h1></body>" 

cleaned = cleanme(testhtml) 
print (cleaned) 

而输出结果只是I need this text captured And this