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

yipeiwu_com5年前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编写简单的画图板程序的示例教程

从这次开始,我会由简单到困难(其实也不会困难到哪里去)讲几个例程,每一个例程都是我自己写(或者修改,那样的话我会提供原始出处)的,都具有一定的操作性和娱乐性。例程中汇尽量覆盖到以前所讲的...

关于ResNeXt网络的pytorch实现

此处需要pip install pretrainedmodels """ Finetuning Torchvision Models """ from __future__ im...

基于windows下pip安装python模块时报错总结

基于windows下pip安装python模块时报错总结

这几天把python版本升级后,发现pip安装模块好多都报错(暂不确定是不是因为升级导致的),我定睛一看,发现是权限的问题,那么怎么解决呢? 1 权限问题 C:\Users\ljf&...

python字符串替换第一个字符串的方法

Python 截取字符串使用 变量[头下标:尾下标],就可以截取相应的字符串,其中下标是从0开始算起,可以是正数或负数,下标可以为空表示取到头或尾。 # 例1:字符串截取 str...

Python中实现的RC4算法

闲暇之时,用Python实现了一下RC4算法 编码 UTF-8 class 方式 #/usr/bin/python #coding=utf-8 import sys,os,hash...