我在处理从不同网页(在不同的网站上)获取的文本中的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()

下面是运行上面的代码段时在某些字符串上生成的堆栈跟踪:

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)

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

有没有人对如何解决这个问题有什么想法,以便我能够始终如一地解决这个问题?


当前回答

这将起作用:

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

输出:

>>>bats

其他回答

我找到了一个很好的方法来删除符号并继续将字符串保持为字符串,如下所示:

yourstring = yourstring.encode('ascii', 'ignore').decode('ascii')

需要注意的是,使用忽略选项是危险的,因为它会默默地从使用它的代码中删除任何unicode(和国际化)支持,如下所示(转换unicode):

>>> u'City: Malmö'.encode('ascii', 'ignore').decode('ascii')
'City: Malm'

这是一个经典的python unicode痛点!考虑以下事项:

a = u'bats\u00E0'
print a
 => batsà

到目前为止一切都很好,但如果我们调用str(a),让我们看看会发生什么:

str(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe0' in position 4: ordinal not in range(128)

噢,滴,这对任何人都没有好处!要修复该错误,请使用.encode显式编码字节,并告诉python要使用的编解码器:

a.encode('utf-8')
 => 'bats\xc3\xa0'
print a.encode('utf-8')
 => batsà

Voil\u00E0!

问题是,当您调用str()时,python使用默认的字符编码来尝试对您给它的字节进行编码,在您的情况下,这些字节有时是unicode字符的表示。要解决这个问题,你必须告诉python如何使用.encode('hatever_unicode')处理你给它的字符串。大多数时候,你应该可以使用utf-8。

有关此主题的精彩阐述,请参阅Ned Batchelder的PyCon演讲:http://nedbatchelder.com/text/unipain.html

我在尝试将Unicode字符输出到stdout时遇到了这个问题,但使用sys.stdout.write,而不是打印(这样我也可以支持输出到其他文件)。

从BeautifulSoup自己的文档中,我用编解码器库解决了这个问题:

import sys
import codecs

def main(fIn, fOut):
    soup = BeautifulSoup(fIn)
    # Do processing, with data including non-ASCII characters
    fOut.write(unicode(soup))

if __name__ == '__main__':
    with (sys.stdin) as fIn: # Don't think we need codecs.getreader here
        with codecs.getwriter('utf-8')(sys.stdout) as fOut:
            main(fIn, fOut)

下面的解决方案对我有效,刚刚补充

u“字符串”

(表示字符串为unicode)。

result_html = result.to_html(col_space=1, index=False, justify={'right'})

text = u"""
<html>
<body>
<p>
Hello all, <br>
<br>
Here's weekly summary report.  Let me know if you have any questions. <br>
<br>
Data Summary <br>
<br>
<br>
{0}
</p>
<p>Thanks,</p>
<p>Data Team</p>
</body></html>
""".format(result_html)

我刚刚遇到了这个问题,谷歌把我带到了这里,所以为了补充这里的一般解决方案,这是对我有用的:

# 'value' contains the problematic data
unic = u''
unic += value
value = unic

我看了奈德的演讲后有了这个想法。

不过,我并没有完全理解为什么这样做有效。所以,如果有人能编辑这个答案或发表评论来解释,我将不胜感激。