我正在尝试用Python3解析和清理一个HTML文件。我正在使用BeautifulSoup的get_text方法,使用lxml作为解析器(以及urllib等)
考虑到iso-8859-1编码的HTML中的you’ve
这样的文本及其“智能”撇号/引号,我很难获得干净的文本,因此它会变成you've
我试着把它通过utf-8再放回去,但它把文本弄得一团糟
课程的一部分:
self.html = response.read()
self.html_parser = BeautifulSoup(self.html, "lxml")
decodedStr = self.html.decode('iso-8859-1')
encodedByt = decodedStr.encode('utf-8')
table = str.maketrans(dict.fromkeys([0x201c, 0x201d, 0x2018, 0x2019]))
encodedStr = str(encodedByt).translate(table)
self.html = encodedStr.encode('iso-8859-1')
有非Ascii字符,“you<0x92>
ve”--所以quopri不适合我
我只是在学习Python,如果您能给我一些建议,让我用一种更地道或更好的方式来学习Python,我将不胜感激。谢谢
更新:
这有助于;似乎str
需要指定编码(除了省略号,这些代码正在被翻译)
transl_table = dict( [ (ord(x), ord(y)) for x,y in zip( u"‘’´“”–-…", u"'''\"\"--\u2606") ] )
encodedStr = str(encodedByt, 'utf-8').translate(transl_table)
self.html = encodedStr.encode('utf-8', 'strict')
试试这个
希望有帮助
相关问题 更多 >
编程相关推荐