本文實例講述了Python轉換HTML到Text純文本的方法。分享給大家供大家參考。具體分析如下:
今天項目需要將HTML轉換為純文本,去網上搜了一下,發現Python果然是神通廣大,無所不能,方法是五花八門。
拿今天親自試的兩個方法舉例,以方便后人:
方法一:
1. 安裝nltk,可以去pipy裝
(注:需要依賴以下包:numpy, PyYAML)
2.測試代碼:
>>> aa = r'''''
???
? Project: DeHTML
? Description :
?This small script is intended to allow conversion from HTML markup to?
?plain text.
???
'''
>>> aa?
'\n\n??????????? \n??????????????? Project: DeHTML
\n??????????????? Description :
\n??????????????? This small script is intended to allow conversion from HTML markup to \n??????????????? plain text.\n??????????? \n??????? \n??????? '?
>>> print nltk.clean_html(aa) ?
Project: DeHTML??
???? Description :??
??? This small script is intended to allow conversion from HTML markup to??
??? plain text.
方法二:
如果覺得nltk太笨重,大材小用的話,可以自己寫代碼,代碼如下:
from re import sub?
from sys import stderr?
from traceback import print_exc?
?
class _DeHTMLParser(HTMLParser):?
??? def __init__(self):?
??????? HTMLParser.__init__(self)?
??????? self.__text = []?
?
??? def handle_data(self, data):?
??????? text = data.strip()?
??????? if len(text) > 0:?
??????????? text = sub('[ \t\r\n]+', ' ', text)?
??????????? self.__text.append(text + ' ')?
?
??? def handle_starttag(self, tag, attrs):?
??????? if tag == 'p':?
??????????? self.__text.append('\n\n')?
??????? elif tag == 'br':?
??????????? self.__text.append('\n')?
?
??? def handle_startendtag(self, tag, attrs):?
??????? if tag == 'br':?
??????????? self.__text.append('\n\n')?
?
??? def text(self):?
??????? return ''.join(self.__text).strip()?
?
?
def dehtml(text):?
??? try:?
??????? parser = _DeHTMLParser()?
??????? parser.feed(text)?
??????? parser.close()?
??????? return parser.text()?
??? except:?
??????? print_exc(file=stderr)?
??????? return text?
?
?
def main():?
??? text = r'''''
???????
???????????
??????????????? Project: DeHTML
??????????????? Description :
??????????????? This small script is intended to allow conversion from HTML markup to?
??????????????? plain text.
???????????
???????
??? '''?
??? print(dehtml(text))?
?
?
if __name__ == '__main__':?
??? main()
運行結果:
>>> ================================ RESTART ================================?
>>>??
Project: DeHTML??
Description :??
This small script is intended to allow conversion from HTML markup to plain text.?
希望本文所述對大家的Python程序設計有所幫助。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
