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程序设计有所帮助。

相关文章

pycharm修改界面主题颜色的方法

pycharm修改界面主题颜色的方法

如下所示: 以上这篇pycharm修改界面主题颜色的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。...

Python利用matplotlib做图中图及次坐标轴的实例

Python利用matplotlib做图中图及次坐标轴的实例

图中图 准备数据 import matplotlib.pyplot as plt fig = plt.figure() x = [1, 2, 3, 4, 5, 6, 7] y =...

Python的Bottle框架的一些使用技巧介绍

之前对bottle做过不少的介绍,也写过一些文章来说明bottle的缺点,最近发现其实之前有些地方说的不太公平,所以趁此机会也来更正一下。     bott...

对python GUI实现完美进度条的示例详解

对python GUI实现完美进度条的示例详解

在用python做一个GUI界面时,想搞一个进度条实时显示下载进度,但查阅很多博客,最后的显示效果都类似下面这种: 这种效果在CMD界面看着还可以,但放到图形界面时就有点丑了,所以我用...

numpy.linspace 生成等差数组的方法

numpy.linspace 生成等差数组的方法

如下所示: numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None) start:...