【问题标题】:UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)UnicodeEncodeError:“ascii”编解码器无法对位置 0-3 中的字符进行编码:序数不在范围内(128)
【发布时间】:2014-08-03 10:01:00
【问题描述】:

当我运行我的代码时,我得到了这个错误:

UserId = "{}".format(source[1]) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

我的代码是:

def view_menu(type, source, parameters):
    ADMINFILE = 'static/users.txt'
    fp = open(ADMINFILE, 'r')
    users = ast.literal_eval(fp.read())
    if not parameters:
        if not source[1] in users:
            UserId = "{}".format(source[1])
            users.append(UserId)
            write_file(ADMINFILE,str(users))
            fp.close()
            reply(type, source, u"test")
        else:
            reply(type, source, u"test")

register_command_handler(view_menu, 'test', ['info','muc','all'], 0, '')

请问我该如何解决这个问题。

谢谢

【问题讨论】:

  • 这里值得指出的是,这个问题正是 Python 3.x 存在的原因。您确定要学习在旧版本语言中混合 Unicode 和非 Unicode 字符串所需的所有笨拙的东西,只是为了在一两年内重新学习所有内容,而不是仅仅学习更容易和更新的东西现在呢?

标签: python python-2.7


【解决方案1】:

问题是"{}" 是非Unicode str,而您正试图将formatunicode 加入其中。 Python 2.x 通过自动将 unicode 编码为 sys.getdefaultencoding()(通常为 'ascii')来处理这个问题,但您有一些非 ASCII 字符。

有两种方法可以解决这个问题:

  1. 在适当的字符集中显式编码 unicode。例如,如果是 UTF-8,则执行 "{}".format(source[1].encode('utf-8'))

  2. 使用unicode 格式字符串:u"{}".format(source[1])。以后你可能还需要encode那个UserId;我不知道你的 write_file 函数是如何工作的。但通常最好让所有 Unicode 内容尽可能长,仅在边缘进行编码和解码,而不是尝试混合和匹配两者。

话虽如此,这行代码毫无用处。 "{}".format(foo)foo 转换为str,然后将其格式化为完全相同的str。为什么?

【讨论】:

  • 谢谢。现在当我使用 "{}".format(source[1].encode('utf-8')) 时它可以工作了
【解决方案2】:

在处理未知编码的字符串时,在此处使用这些函数:

您想处理文本吗?

def read_unicode(text, charset='utf-8'):
    if isinstance(text, basestring):
        if not isinstance(text, unicode):
            text = unicode(obj, charset)
    return text

你想存储文本,例如在数据库中,使用这个:

def write_unicode(text, charset='utf-8'):
    return text.encode(charset)

【讨论】:

    【解决方案3】:

    解决方案是在您的 sitecustomize.py 中将默认编码设置为 utf-8 而不是 ascii

    Changing default encoding of Python?

    【讨论】:

      【解决方案4】:

      您的文件 static/users.txt 必须包含任何非 Unicode 字符。您必须在程序中指定任何编码。对于 intsnace utf-8。你可以在这里阅读更多信息:Unicode HOWTO

      【讨论】:

      • 一个字符,其身份不是通过 Unicode 表分配的。
      • @amatellanes 请你检查一下这个问题http://stackoverflow.com/questions/25088887/nimbuzz-login-config-code-dosnt-work 并帮助我解决我的问题。
      • @amatellanes:他的文件几乎可以肯定不包含任何非 Unicode 字符。而且,如果是这样,UTF-8 也无济于事,因为 UTF-8 只编码 Unicode 字符。
      猜你喜欢
      • 1970-01-01
      • 2012-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-22
      • 1970-01-01
      • 2017-10-13
      相关资源
      最近更新 更多