HTML:在Python 3中将iso-8859-1编码的智能引号转换为简单引号

问题描述 投票:0回答:1

[我正在尝试使用Python 3解析和清理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,并且希望以更惯用或更好的方式进行此操作。谢谢。

更新:

这有帮助;似乎需要指定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')
python python-3.x beautifulsoup lxml
1个回答
1
投票

尝试一下

table = str.maketrans({'’': "'"})

希望有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.