关键词不能为空

当前您在: 主页 > 英语 >

Python转换HTML到Text纯文本的方法

作者:高考题库网
来源:https://www.bjmy2z.cn/gaokao
2021-02-18 03:02
tags:

-

2021年2月18日发(作者:soulmate是什么意思)


Python


转换


HTML


Text


纯文本的方法








本文实例讲述了


Python


转换


HTML



Te xt


纯文本的方


法。分享给大家供大家参考。具体分析如下:< /p>



今天项目需要将


HTML


转换为纯文本,


去网上搜了一下,




Python


果然是神通广大,无所不能,方法是五 花八门。



拿今天亲自试的两个方法举例,以方便后人:



方法一:



1.

安装


nltk


,可以去


pipy< /p>




(注:需要依赖以下包:


numpy, PyYAML




2.


测试代码:




复制代码



代码如下


:


>>> import nltk




>>> aa = r'''''



<html>







<body>




<b>Project:</b> DeHTML<br>



<b>Description</b>:<br>




This small script is intended to allow conversion from HTML


markup to





plain text.







</body>



</html>



'''


>>> aa




'n<html>n













<body>n

















<b>Project:</b> DeHTML<br>n

















<b>Description</b& gt;:<br>n

















This small script is intended to allow conversion from HTML


markup to n

















plain text.n













</body>n









</html>n









'




>>> <strong>print


_html(aa)</strong>




Project: DeHTML










Description :









This small script is intended to allow conversion from


HTML markup to









plain text.



方法二:



如果觉得

< br>nltk


太笨重,大材小用的话,可以自己写代码,代


码 如下


:



复制代码



代码如下


:


from HTMLParser import HTMLParser




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 = ()












if len(text) > 0:
















text = sub('[ trn]+', ' ', text)
















self.__(text + ' ')











def handle_starttag(self, tag, attrs):












if tag == 'p':
















self.__('nn')












elif tag == 'br':
















self.__('n')



-


-


-


-


-


-


-


-



本文更新与2021-02-18 03:02,由作者提供,不代表本网站立场,转载请注明出处:https://www.bjmy2z.cn/gaokao/664135.html

Python转换HTML到Text纯文本的方法的相关文章