regex - "UnicodeEncodeError: ' ascii ' codec can' t 编码字符"

标签 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()

最佳答案

您正在尝试在“严格”模式下将 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

关于regex - "UnicodeEncodeError: ' ascii ' codec can' t 编码字符",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1652904/

相关文章:

python - CentOS从Python2.4过渡到Python2.6,模块迁移问题

python - 从 optparse 传递可选参数

.net - 正则表达式查找未注释掉的标签之间的文本

regex - 从字符串中提取和合并数字

java - 如何使用正则表达式从该行中提取子字符串

html - 如何在手机上显示汉堡图标 "☰"?

java - 对 ISO-8859-1 编码的 XML 文档中的 Unicode 字符进行解码

regex - 使用 sed 提取子字符串

unicode - 是否可以使用 Unicode 输入注音假名(和 Ruby 字符)?

Windows 上的 Python 2.6 : how to terminate subprocess. Popen 带有 "shell=True"参数?