【问题标题】:UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)UnicodeEncodeError:“ascii”编解码器无法在位置 20 编码字符 u'\xa0':序数不在范围内(128)
【发布时间】:2012-04-14 02:47:17
【问题描述】:

我在处理从不同网页(在不同网站上)提取的文本中的 unicode 字符时遇到问题。我正在使用 BeautifulSoup。

问题在于错误并不总是可重现的;它有时适用于某些页面,有时,它会通过抛出UnicodeEncodeError 而失败。我已经尝试了几乎所有我能想到的东西,但我还没有找到任何能始终如一地工作而不会引发某种与 Unicode 相关的错误的东西。

导致问题的代码部分如下所示:

agent_telno = agent.find('div', 'agent_contact_number')
agent_telno = '' if agent_telno is None else agent_telno.contents[0]
p.agent_info = str(agent_contact + ' ' + agent_telno).strip()

这是运行上面的 sn-p 时在一些字符串上产生的堆栈跟踪:

Traceback (most recent call last):
  File "foobar.py", line 792, in <module>
    p.agent_info = str(agent_contact + ' ' + agent_telno).strip()
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

我怀疑这是因为某些页面(或者更具体地说,来自某些网站的页面)可能已编码,而其他页面可能未编码。所有网站都位于英国,并提供用于英国消费的数据 - 因此不存在与内部化或处理以英语以外的任何文字编写的文本相关的问题。

是否有人对如何解决此问题有任何想法,以便我可以始终如一地解决此问题?

【问题讨论】:

  • 如果您作为用户而不是作为开发人员遇到这些错误,请检查serverfault.com/questions/54591/… 和askubuntu.com/questions/599808/…
  • 我会补充一点,不要使用onlinegdb.com/online_python_interpreter 来处理这些东西。正在使用该解释器来试用一些东西,但它没有为 Unicode 正确配置!总是以 'B'\nnn'' 格式打印...而我想要的只是一个 guillemet!在虚拟机上试过,它使用 chr() 立即按预期工作
  • 试试这个import os; import locale; os.environ["PYTHONIOENCODING"] = "utf-8"; myLocale=locale.setlocale(category=locale.LC_ALL, locale="en_GB.UTF-8"); ... print(myText.encode('utf-8', errors='ignore'))。
  • @hhh 我跑了你的 sn-p NameError: name 'myText' is not defined
  • 尝试在shell中设置PYTHONIOENCODING,然后再执行你的脚本:$ export PYTHONIOENCODING=utf8

标签: python unicode beautifulsoup python-2.x python-unicode


【解决方案1】:

这个问题经常发生在 django 项目使用 Apache 部署时。因为 Apache 在 /etc/sysconfig/httpd 中设置了环境变量 LANG=C。只需打开文件并评论(或更改为您的风格)此设置。或者使用 WSGIDaemonProcess 命令的 lang 选项,这样你就可以为不同的虚拟主机设置不同的 LANG 环境变量。

【讨论】:

    【解决方案2】:

    这会起作用:

     >>>print(unicodedata.normalize('NFD', re.sub("[\(\[].*?[\)\]]", "", "bats\xc3\xa0")).encode('ascii', 'ignore'))
    

    输出:

    >>>bats
    

    【讨论】:

      【解决方案3】:

      您可以在运行脚本之前将字符编码设置为UTF-8:

      export LC_CTYPE="en_US.UTF-8"
      

      这通常应该可以解决问题。

      【讨论】:

        【解决方案4】:

        您可以使用 unicodedata 来避免 UnicodeEncodeError。这是一个例子:

        import unicodedata
        
        agent_telno = agent.find('div', 'agent_contact_number')
        agent_telno = unicodedata.normalize("NFKD", agent_telno) #it will remove all unwanted character like '\xa0'
        agent_telno = '' if agent_telno is None else agent_telno.contents[0]
        p.agent_info = str(agent_contact + ' ' + agent_telno).strip()
        

        【讨论】:

          猜你喜欢
          • 2018-07-10
          • 2020-04-04
          • 2016-08-26
          • 2017-03-29
          • 2011-07-05
          • 2016-09-05
          • 2013-02-11
          • 2012-05-06
          • 2019-12-15
          相关资源
          最近更新 更多