27

我正在尝试通过正则表达式传递大量随机 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

4 回答 4

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
于 2009-10-31T00:58:40.527 回答
22

您正在尝试将字节串传递给某些东西,但是(从您提供的信息的稀缺性来看)不可能告诉您要将其传递给什么。您从一个无法编码为 ASCII(默认编解码器)的 Unicode 字符串开始,因此,您必须通过一些不同的编解码器进行编码(或按照@R.Pate 的建议对其进行音译)——但这不可能用于说出你应该使用什么编解码器,因为我们不知道你传递的字节串是什么,因此不知道那个未知子系统将能够在编解码器方面正确接受和处理什么。

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

传递thestring.encode('utf-8')而不是直接传递thestring肯定会避免您现在看到的特定错误,但它可能会导致特殊的显示(或您尝试使用该字节串做的任何事情!)除非接收者准备好、愿意并且能够接受 utf-8 编码(我们怎么知道,对接收者可能是什么完全零概念?!-)

于 2009-10-31T01:12:21.430 回答
1

“最佳”方式始终取决于您的要求;那么,你的呢?忽略非ASCII合适吗?你应该用“(tm)”替换™吗?(这个例子看起来很花哨,但对于其他代码点来说很快就崩溃了——但它可能正是你想要的。)这个异常是否正是你所需要的?现在你只需要以某种方式处理它?

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

于 2009-10-31T00:31:55.477 回答
0

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

sudo apt-get install language-pack-en

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

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

例如:

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

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

于 2015-08-13T12:11:57.910 回答