• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

python 搞代码 4年前 (2022-01-08) 65次浏览 已收录 0个评论

这篇文章主要介绍了Python转换HTML到Text纯文本的方法,分析了常用的两种方法,非常具有实用价值,需要的朋友可以参考下

本文实例讲述了Python转换HTML到Text纯文本的方法。分享给大家供大家参考。具体分析如下:

今天项目需要将HTML转换为纯文本,去网上搜了一下,发现Python果然是神通广大,无所不能,方法是五花八门。

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

方法一:

1. 安装nltk,可以去pipy装

(注:需要依赖以下包:numpy, PyYAML)

2.测试代码:

代码如下:
>>> import nltk 
>>> 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 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 来源gaodai#ma#com搞*代#码网= [] 
 
    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程序设计有所帮助。

以上就是Python转换HTML到Text纯文本的方法的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python转换HTML到Text纯文本的方法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址