我正在写一个程序在googleappengine上运行。它只需获取一个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'
^{pr2}$但是,它为“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\u html. 在
这是因为unicode和bytestrings之间存在混合。在
如果在模块中使用HtmlTool
为了确保每个
^{pr2}$" "
类块都是unicode,并且向方法发送一个UTF-8字符串,这就解决了您的问题。在
有关Unicode的详细信息,请阅读以下内容: http://www.joelonsoftware.com/articles/Unicode.html
相关问题 更多 >
编程相关推荐