Python 将HTML转换为可读文本
我正在写一个在谷歌应用程序引擎上运行的程序。它只需获取一个URL,并通过从其HTML源中删除标记、脚本和任何其他不可读的内容(类似于nltk.clear_HTML)来返回文本 HtmlTool由 但是,它为“”抛出了一个错误 错误:Python 将HTML转换为可读文本,python,html,regex,nltk,Python,Html,Regex,Nltk,我正在写一个在谷歌应用程序引擎上运行的程序。它只需获取一个URL,并通过从其HTML源中删除标记、脚本和任何其他不可读的内容(类似于nltk.clear_HTML)来返回文本 HtmlTool由 但是,它为“”抛出了一个错误 错误: Traceback (most recent call last): File "C:\Users\BK\Desktop\Working Folder\AppEngine\crawlnsearch\-test.py", line 51, in <modul
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)
回溯(最近一次呼叫最后一次):
文件“C:\Users\BK\Desktop\Working Folder\AppEngine\crawnsearch \-test.py”,第51行,在
text=HtmlTool.to_nice_text(urllib.urlopen('http://yahoo.com“).read())
文件“C:\Users\BK\Desktop\Working Folder\AppEngine\crawnsearch \-test.py”,第43行,以文本形式显示
text=HtmlTool.html\u parser.unescape(text)
文件“C:\Python27\lib\HTMLParser.py”,第472行,在unescape中
返回RER.sub(r“&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));”,替换实体,s)
文件“C:\Python27\lib\re.py”,第151行,子文件
return\u compile(模式、标志).sub(repl、字符串、计数)
UnicodeDecodeError:“ascii”编解码器无法解码位置1531处的字节0xe0:序号不在范围内(128)
那么,有谁能解释一下这段代码有什么问题,并对此进行修复,或者请告诉我如何使用nltk.clean_html。这是因为unicode和ByTestRing混合使用 如果在模块中与HTMLTOL一起使用
from __future__ import unicode_literals
确保每个类似于的块都是unicode的,并且
text = HtmlTool.to_nice_text(urllib.urlopen(url).read().decode("utf-8"))
向方法发送UTF-8字符串,这就解决了问题
有关Unicode的更多信息,请阅读此文档:
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)
from __future__ import unicode_literals
text = HtmlTool.to_nice_text(urllib.urlopen(url).read().decode("utf-8"))