2017-10-10 11 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/software/BeautifulSoup/bs4/doc /#get-text)。 –

答えて

0

あなたは本当にこのためにBeautifulSoupを使用する必要があります。 pip3 install BeautifulSoup4またはpip install BeautifulSoup4は、必要なPythonのバージョンによって異なります。私はすでに同様の質問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になります。

関連する問題