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

yipeiwu_com6年前Python基础

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

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

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

方法一:

1. 安装nltk,可以去pipy装

(注:需要依赖以下包: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>:<br>\n                This small script is intended to allow conversion from HTML markup to \n                plain text.\n            </body>\n        </html>\n        ' 
>>> <strong>print nltk.clean_html(aa)</strong> 
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 = [] 
 
    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'''''
        <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>
    ''' 
    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 多核并行计算的示例代码

Python 多核并行计算的示例代码

以前写点小程序其实根本不在乎并行,单核跑跑也没什么问题,而且我的电脑也只有双核四个超线程(下面就统称核好了),觉得去折腾并行没啥意义(除非在做IO密集型任务)。然后自从用上了32核128...

python实现差分隐私Laplace机制详解

python实现差分隐私Laplace机制详解

Laplace分布定义: 下面先给出Laplace分布实现代码: import matplotlib.pyplot as plt import numpy as np def...

用实例说明python的*args和**kwargs用法

先来看一个例子:复制代码 代码如下:>>> def foo(*args, **kwargs):    print 'args =', ar...

基于wxPython的GUI实现输入对话框(2)

基于wxPython的GUI实现输入对话框(2)

接着上一篇基于wxPython的GUI输入对话框1,继续学习。 在程序输入中,有时会要求同时改变多个参数值,而且类型也不尽相同, 这时TextEntryDialog就显得不适用了.WxI...

使用简单工厂模式来进行Python的设计模式编程

使用简单工厂模式来进行Python的设计模式编程

计模式的目的是让代码易维护、易扩展,不能为了模式而模式,因此一个简单的工具脚本是不需要用到任何模式的。 简单工厂模式又叫静态工厂方法模式,工厂模式家族中最简单的一种模式。这个模式的基本工...