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

Ken*_*an1 27 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)
Run Code Online (Sandbox Code Playgroud)

完整脚本:

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()
Run Code Online (Sandbox Code Playgroud)

Set*_*eth 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.
Run Code Online (Sandbox Code Playgroud)

您可能想要类似下列之一:

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
Run Code Online (Sandbox Code Playgroud)


Ale*_*lli 21

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

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

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