“UnicodeEncodeError:'ascii'编解码器无法编码字符”

时间:2009-10-31 00:07:49

标签: regex unicode python-2.6 non-ascii-characters

我正在尝试通过正则表达式传递随机html的大字符串,我的Python 2.6脚本对此感到窒息:

UnicodeEncodeError:'ascii'编解码器无法编码字符

我追溯到这个词末尾的商标上标:Protection™ - 我希望将来会遇到其他类似的人。

是否有处理非ascii字符的模块?或者,在python中处理/转义非ascii内容的最佳方法是什么?

谢谢! 完整错误:

E
======================================================================
ERROR: test_untitled (__main__.Untitled)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Python26\Test2.py", line 26, in test_untitled
    ofile.write(Whois + '\n')
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2122' in position 1005: ordinal not in range(128)

完整脚本:

from selenium import selenium
import unittest, time, re, csv, logging

class Untitled(unittest.TestCase):
    def setUp(self):
        self.verificationErrors = []
        self.selenium = selenium("localhost", 4444, "*firefox", "http://www.BaseDomain.com/")
        self.selenium.start()
        self.selenium.set_timeout("90000")

    def test_untitled(self):
        sel = self.selenium
        spamReader = csv.reader(open('SubDomainList.csv', 'rb'))
        for row in spamReader:
            sel.open(row[0])
            time.sleep(10)
            Test = sel.get_text("//html/body/div/table/tbody/tr/td/form/div/table/tbody/tr[7]/td")
            Test = Test.replace(",","")
            Test = Test.replace("\n", "")
            ofile = open('TestOut.csv', 'ab')
            ofile.write(Test + '\n')
            ofile.close()

    def tearDown(self):
        self.selenium.stop()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()

4 个答案:

答案 0 :(得分:32)

您正试图在“严格”模式下将unicode转换为ascii:

>>> help(str.encode)
Help on method_descriptor:

encode(...)
    S.encode([encoding[,errors]]) -> object

    Encodes S using the codec registered for encoding. encoding defaults
    to the default encoding. errors may be given to set a different error
    handling scheme. Default is 'strict' meaning that encoding errors raise
    a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
    'xmlcharrefreplace' as well as any other name registered with
    codecs.register_error that is able to handle UnicodeEncodeErrors.

您可能需要以下某项内容:

s = u'Protection™'

print s.encode('ascii', 'ignore')    # removes the ™
print s.encode('ascii', 'replace')   # replaces with ?
print s.encode('ascii','xmlcharrefreplace') # turn into xml entities
print s.encode('ascii', 'strict')    # throw UnicodeEncodeErrors

答案 1 :(得分:21)

您正在尝试将字节字符串传递给某些内容,但是不可能(根据您提供的信息的稀缺性)告诉您想要传递给它的。你从一个不能编码为ASCII(默认编解码器)的Unicode字符串开始,所以,你必须用一些不同的编解码器进行编码(或者音译,如@ R.Pate建议的那样) - 但它不可能用于说你应该使用什么编解码器,因为我们不知道你传递的字节串是什么,因此不知道那个未知子系统能够接受和正确处理的是什么编解码器。

在你离开我们的完全黑暗中,utf-8是一个合理的盲目猜测(因为它是一个编解码器,可以将任何Unicode字符串完全表示为字节串,并且它是用于许多目的的标准编解码器,例如XML) - 但它不能只是一个盲目的猜测,除非你要告诉我们更多关于什么你试图将那个字节串传递给什么,以及为什么目的。

传递thestring.encode('utf-8')而非裸thestring肯定会避免您现在看到的特定错误,但这可能会导致特殊的显示(或者 你'尝试使用那个字节串!)除非收件人准备好,愿意并且能够接受utf-8编码(我们怎么知道,对接收者可能是什么绝对不知道?! - )

答案 2 :(得分:1)

“最佳”方式总是取决于您的要求;那么,你的是什么?是否忽略非ASCII适当?你应该用“(tm)”替换™吗? (这个例子看起来很花哨,但很快就会破坏其他代码点 - 但它可能正是你想要的。)异常可能正是你所需要的;现在你只需要以某种方式处理它?<​​/ p>

只有你能真正回答这个问题。

答案 3 :(得分:0)

首先,尝试安装英语翻译(或其他任何需要的翻译):

sudo apt-get install language-pack-en

为所有支持的软件包(包括Python)提供翻译数据更新。

并确保在代码中使用正确的编码。

例如:

open(foo, encoding='utf-8')

然后仔细检查您的系统配置,例如LANG的值或区域设置的配置(/etc/default/locale),并且不要忘记重新登录您的会话。