Skip to main content
 首页 » 编程设计

python之在 Python 中将多字节字符转换为 7 位 ASCII

2025年04月02日15qq号

我正在通过 Python 脚本下载和解析网页。我需要它 编码为 7 位 ASCII 以供进一步处理。我正在使用 请求库(http://docs.python-requests.org/en/master/)在 基于 Ubuntu 16.04 LTS 的 virtualenv。

我想要请求包或某个包来处理 翻译成 ASCII,不需要我做进一步的翻译 编码字符,因为我知道我会错过一些 人物。详情如下:

我当前的 Python 脚本(如下所示)使用 ISO-8859-1 编码 试图强制将结果数据转换为 7 位 ASCII, 取得了部分成功。但是,我设置了结果编码和 出来的时候还要对文本进行编码。这看起来很奇怪,事实上, 大错特错。但即使我接受了,我也有主要问题 如下:

即使在编码之后,我也看到破折号编码在似乎是 一些非 ASCII 字符集。好像破折号字符滑了 通过请求编码。下面的脚本解决了这个问题 搜索并用 ASCII 替换多字节破折号编码 破折号字符。如果它是一个多字节,这没什么大不了的 字符,但怀疑还有其他字符需要 在我希望处理的其他网页中翻译。我只是 需要使用“ISO-8859-1”以外的其他编码 请求对象?

这是我的脚本(在 x86_64 上的 Ubuntu 16.04 LTS 上使用 Python 2.7.11):

 #!/bin/bash 
 
 import sys 
 import os 
 import string 
 import re 
 import requests 
 
 url = "https://system76.com/laptops/kudu" 
 
 r = requests.get(url) 
 
 # 
 # Why do I have to BOTH set r.encoding AND call r.text.encode 
 # in order to avoid the errors?: 
 # 
 encoding = 'ISO-8859-1' 
 r.encoding = encoding 
 data = r.text.encode(encoding) 
 
 # 
 # Split the lines out, find the offending line, 
 # and translate the multi-byte characters: 
 # 
 lines = data.splitlines() 
 for line in lines: 
     m = re.search(r'2.6 up to 3.5 GHz', line) 
     if m: 
         print "line:      {}".format(line) 
         m = re.search(r'\xe2\x80\x93', line) 
         # The '-' in the next line is a ASCII dash character: 
         fixed_line = re.sub(r'\xe2\x80\x93', '-', line) 
         print "fixed_line {}".format(line) 

在 virtualenv 中调用 simple_wget.py 显示:

theuser@thesystem:~$ simple_wget.py 
line:                           <td>2.6 up to 3.5 GHz – 6 MB cache – 4 cores – 8 threads</td> 
fixed_line                      <td>2.6 up to 3.5 GHz - 6 MB cache - 4 cores - 8 threads</td> 

通过 oc -cb 传递该输出以查看八进制值(“342 200 223")中的r'\xe2\x80\x93'对应的破折号 上面的脚本:

theuser@thesystem:~$ simple_wget.py | od -cb 
0000000   l   i   n   e   :                          \t  \t  \t  \t  \t 
        154 151 156 145 072 040 040 040 040 040 040 011 011 011 011 011 
0000020  \t   <   t   d   >   2   .   6       u   p       t   o       3 
        011 074 164 144 076 062 056 066 040 165 160 040 164 157 040 063 
0000040   .   5       G   H   z     342 200 223       6       M   B     
        056 065 040 107 110 172 040 342 200 223 040 066 040 115 102 040 
0000060   c   a   c   h   e     342 200 223       4       c   o   r   e 
        143 141 143 150 145 040 342 200 223 040 064 040 143 157 162 145 
0000100   s     342 200 223       8       t   h   r   e   a   d   s   < 
        163 040 342 200 223 040 070 040 164 150 162 145 141 144 163 074 
0000120   /   t   d   >  \n   f   i   x   e   d   _   l   i   n   e     
        057 164 144 076 012 146 151 170 145 144 137 154 151 156 145 040 
0000140  \t  \t  \t  \t  \t  \t   <   t   d   >   2   .   6       u   p 
        011 011 011 011 011 011 074 164 144 076 062 056 066 040 165 160 
0000160       t   o       3   .   5       G   H   z       -       6     
        040 164 157 040 063 056 065 040 107 110 172 040 055 040 066 040 
0000200   M   B       c   a   c   h   e       -       4       c   o   r 
        115 102 040 143 141 143 150 145 040 055 040 064 040 143 157 162 
0000220   e   s       -       8       t   h   r   e   a   d   s   <   / 
        145 163 040 055 040 070 040 164 150 162 145 141 144 163 074 057 
0000240   t   d   >  \n 
        164 144 076 012 
0000244 
theuser@thesystem:~$ 

我尝试过的事情:

https://stackoverflow.com/a/19645137/257924暗示使用编码 ascii,但它在请求库中阻塞。改变 脚本为:

#encoding = 'ISO-8859-1' 
encoding = 'ascii' # try https://stackoverflow.com/a/19645137/257924 
r.encoding = encoding 
data = r.text.encode(encoding) 

产量:

theuser@thesystem:~$ ./simple_wget 
Traceback (most recent call last): 
  File "./simple_wget.py", line 18, in <module> 
    data = r.text.encode(encoding) 
UnicodeEncodeError: 'ascii' codec can't encode characters in position 10166-10168: ordinal not in range(128) 

将上面的最后一行更改为

data = r.text.encode(encoding, "ignore") 

导致破折号只是被删除,而不是翻译,这不是我想要的。

这也根本不起作用:

encoding = 'ISO-8859-1' 
r.encoding = encoding 
data = r.text.encode(encoding) 
 
charmap = { 
    0x2014: u'-',   # em dash 
    0x201D: u'"',   # comma quotation mark, double 
    # etc. 
} 
data = data.translate(charmap) 

因为它给出了这个错误:

Traceback (most recent call last): 
  File "./simple_wget.py", line 30, in <module> 
    data = tmp2.translate(charmap) 
TypeError: expected a string or other character buffer object 

据我所知 https://stackoverflow.com/a/10385520/257924 ,由于“数据”不是 统一码字符串。一个 256 个字符的翻译表是行不通的 无论如何我需要什么。除此之外,还有一些矫枉过正:内在的东西 Python 应该翻译这些多字节字符而不需要 在我的脚本级别破解代码。

顺便说一句,我对多语言页面翻译不感兴趣。全部 翻译的页面应使用美国或英国英语。

请您参考如下方法:

Python 拥有干净地处理非 ASCII 字符所需的一切...只要您声明正确的编码。您的输入文件是 UTF8 编码的,而不是 ISO-8859-1,因为 r'\xe2\x80\x93'是 EN DASH 字符或 unicode 的 UTF8 编码 U+2013 .

所以你应该:

  • 将请求中的文本作为真正的 unicode 字符串加载:

    url = "https://system76.com/laptops/kudu" 
     
    r = requests.get(url) 
    r.encoding = "UTF-8" 
    data = r.text  # ok, data is a true unicode string 
    
  • 翻译违规字符unicode:

    charmap = { 
        0x2014: u'-',   # em dash 
        0x201D: u'"',   # comma quotation mark, double 
        # etc. 
    } 
    data = data.translate(charmap) 
    

    它现在可以工作了,因为 translate map 对于 byte 和 unicode 字符串是不同的。对于字节字符串,转换表必须是长度为 256 的字符串,而对于 unicode 字符串,它必须是 Unicode 序数到 Unicode 序数、Unicode 字符串或无 (ref: Python Standard Library Reference Manual) 的映射。

  • 然后您可以安全地将数据编码为 ascii 字节字符串:

    tdata = data.encode('ascii') 
    

    如果 data 中仍有一些未翻译的非 ascii 字符,上述命令将抛出异常统一码字符串。您可以将其视为确保所有内容都已成功转换的帮助。