HTML到可读文本

时间:2013-08-31 03:48:05

标签: python html regex nltk

我正在编写一个在Google App Engine上运行的程序。只需获取一个URL并通过从HTML源代码中删除标记,脚本和任何其他不可读的内容来返回文本(类似于nltk.clear_html)。

HtmlTool Eike

import urllib

class HtmlTool(object):
    import HTMLParser
    import re
    """
    Algorithms to process HTML.
    """
    #Regular expressions to recognize different parts of HTML. 
    #Internal style sheets or JavaScript 
    script_sheet = re.compile(r"<(script|style).*?>.*?(</\1>)", 
                              re.IGNORECASE | re.DOTALL)
    #HTML comments - can contain ">"
    comment = re.compile(r"<!--(.*?)-->", re.DOTALL) 
    #HTML tags: <any-text>
    tag = re.compile(r"<.*?>", re.DOTALL)
    #Consecutive whitespace characters
    nwhites = re.compile(r"[\s]+")
    #<p>, <div>, <br> tags and associated closing tags
    p_div = re.compile(r"</?(p|div|br).*?>", 
                       re.IGNORECASE | re.DOTALL)
    #Consecutive whitespace, but no newlines
    nspace = re.compile("[^\S\n]+", re.UNICODE)
    #At least two consecutive newlines
    n2ret = re.compile("\n\n+")
    #A return followed by a space
    retspace = re.compile("(\n )")

    #For converting HTML entities to unicode
    html_parser = HTMLParser.HTMLParser()

    @staticmethod
    def to_nice_text(html):
        """Remove all HTML tags, but produce a nicely formatted text."""
        if html is None:
            return u""
        text = html
        text = HtmlTool.script_sheet.sub(" ", text)
        text = HtmlTool.comment.sub(" ", text)
        text = HtmlTool.nwhites.sub(" ", text)
        text = HtmlTool.p_div.sub("\n", text) #convert <p>, <div>, <br> to "\n"
        text = HtmlTool.tag.sub(" ", text)     #remove all tags
        text = HtmlTool.html_parser.unescape(text)
        #Get whitespace right
        text = HtmlTool.nspace.sub(" ", text)
        text = HtmlTool.retspace.sub("\n", text)
        text = HtmlTool.n2ret.sub("\n\n", text)
        text = text.strip()
        return text

适用于“http://google.com

text = HtmlTool.to_nice_text(urllib.urlopen('http://google.com').read())

但是,它会为“http://yahoo.com

引发错误
text = HtmlTool.to_nice_text(urllib.urlopen('http://yahoo.com').read())

错误:

Traceback (most recent call last):
  File "C:\Users\BK\Desktop\Working Folder\AppEngine\crawlnsearch\-test.py", line 51, in <module>
    text = HtmlTool.to_nice_text(urllib.urlopen('http://yahoo.com').read())
  File "C:\Users\BK\Desktop\Working Folder\AppEngine\crawlnsearch\-test.py", line 43, in to_nice_text
    text = HtmlTool.html_parser.unescape(text)
  File "C:\Python27\lib\HTMLParser.py", line 472, in unescape
    return re.sub(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));", replaceEntities, s)
  File "C:\Python27\lib\re.py", line 151, in sub
    return _compile(pattern, flags).sub(repl, string, count)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe0 in position 1531: ordinal not in range(128)

那么,任何人都可以解释这段代码的错误并发布修复程序,或者请告诉我如何使用nltk.clean_html。

1 个答案:

答案 0 :(得分:1)

那是因为unicode和bytestrings之间存在混合。

如果您在模块中使用HtmlTool

from __future__ import unicode_literals

确保每个" "类似的块都是unicode,并且

text = HtmlTool.to_nice_text(urllib.urlopen(url).read().decode("utf-8"))

向您的方法发送UTF-8字符串,以解决您的问题。

有关Unicode的更多信息,请阅读此内容: http://www.joelonsoftware.com/articles/Unicode.html

相关问题