【问题标题】:handle non ascii code string in python在python中处理非ASCII码字符串
【发布时间】:2013-03-22 03:35:53
【问题描述】:

在 python 中处理非 ascii 代码字符真的很令人困惑。谁能解释一下?

我正在尝试读取纯文本文件并将所有非字母字符替换为空格。

我有一个字符列表:

ignorelist = ('!', '-', '_', '(', ')', ',', '.', ':', ';', '"', '\'', '?', '#', '@', '$', '^', '&', '*', '+', '=', '{', '}', '[', ']', '\\', '|', '<', '>', '/', u'—')

对于我得到的每个令牌,我通过调用用空格替换该令牌中的任何字符

    for punc in ignorelist:
        token = token.replace(punc, ' ')

注意ignorelist 末尾有一个非 ascii 代码字符:u'—'

每当我的代码遇到该字符时,它都会崩溃并说:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position

我尝试通过在文件顶部添加# -*- coding: utf-8 -*- 来声明编码,但仍然无法正常工作。有谁知道为什么?谢谢!

【问题讨论】:

    标签: python unicode encoding decoding non-ascii-characters


    【解决方案1】:

    您的文件输入不是 utf-8。因此,当您点击该 unicode 字符时,您的输入会在比较中出现错误,因为它将您的输入视为 ascii。

    尝试用这个来读取文件。

    import codecs
    f = codecs.open("test", "r", "utf-8")
    

    【讨论】:

    • 我想给你点赞。但我的分数低于 15 分,我不能投票……抱歉!
    【解决方案2】:

    您使用的是 Python 2.x,它会尝试自动转换 unicodes 和普通的 strs,但它通常会因非 ascii 字符而失败。

    您不应将unicodes 和strs 混合在一起。你可以坚持unicodes:

    ignorelist = (u'!', u'-', u'_', u'(', u')', u',', u'.', u':', u';', u'"', u'\'', u'?', u'#', u'@', u'$', u'^', u'&', u'*', u'+', u'=', u'{', u'}', u'[', u']', u'\\', u'|', u'<', u'>', u'/', u'—')
    
    if not isinstance(token, unicode):
        token = token.decode('utf-8') # assumes you are using UTF-8
    for punc in ignorelist:
        token = token.replace(punc, u' ')
    

    或者只使用普通的strs(注意最后一个):

    ignorelist = ('!', '-', '_', '(', ')', ',', '.', ':', ';', '"', '\'', '?', '#', '@', '$', '^', '&', '*', '+', '=', '{', '}', '[', ']', '\\', '|', '<', '>', '/', u'—'.encode('utf-8'))
    # and other parts do not need to change
    

    通过手动将您的u'—' 编码为str,Python 无需自行尝试。

    我建议您在整个程序中使用unicode 以避免此类错误。但如果工作量太大,您可以使用后一种方法。但是,在调用标准库或第三方模块中的某些函数时要小心。

    # -*- coding: utf-8 -*- 只告诉 Python 你的代码是用 UTF-8 编写的(或者你会得到一个SyntaxError)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-11
      • 2014-02-27
      • 2013-07-13
      • 1970-01-01
      • 2015-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多