本文實(shí)例講述了Python轉(zhuǎn)換HTML到Text純文本的方法。分享給大家供大家參考。具體分析如下:
今天項(xiàng)目需要將HTML轉(zhuǎn)換為純文本,去網(wǎng)上搜了一下,發(fā)現(xiàn)Python果然是神通廣大,無(wú)所不能,方法是五花八門。
拿今天親自試的兩個(gè)方法舉例,以方便后人:
方法一:
1. 安裝nltk,可以去pipy裝
(注:需要依賴以下包:numpy, PyYAML)
2.測(cè)試代碼:
>>> 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.
方法二:
如果覺(jué)得nltk太笨重,大材小用的話,可以自己寫(xiě)代碼,代碼如下:
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()
運(yùn)行結(jié)果:
>>> ================================ RESTART ================================?
>>>??
Project: DeHTML??
Description :??
This small script is intended to allow conversion from HTML markup to plain text.?
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

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