0

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

Eike的 HtmlTool 。

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。

4

1 回答 1

1

那是因为 unicode 和字节串之间存在混合。

如果您在带有 HtmlTool 的模块中使用

from __future__ import unicode_literals

确保每个" "-like 块都是 unicode,并且

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

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

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

于 2013-08-31T04:09:26.187 回答