【问题标题】:trying to understand a Python Unicode exception试图理解 Python Unicode 异常
【发布时间】:2013-05-20 20:34:58
【问题描述】:

我有一个未指定类型的字符串对象。它将匹配 types.StringTypes,但可能是 type.StringType 或 type.UnicodeType - 我不确定我会收到什么。我不一定能控制进来的东西。

当我在字符串类型中有一个非 ascii 字符并将调用传递给 misaka(这是一个 sundown 解析器)时,就会出现我的问题

在这个例子中,我们正在处理 unichr(8250) / u'\u203a' ,这在我的错误日志中导致了几次......

a = "›"
b = u"›"

print type(a) # <type 'str'>
print type(b) # <type 'unicode'>

print a # fine
print b # fine

import misaka

markdown_renderer = misaka.HtmlRenderer()
renderer = misaka.Markdown( markdown_renderer )

try:
    print renderer.render( a )
    #this will fail
    print "GOOD a"
except:
    print "FAILED a"

try:
    print renderer.render( b )
    #this will pass
    print "GOOD b"
except:
    print "FAILED b"

我不知道如何将“a”对象变成 misaka 不会有问题的东西。 'b' 总是有效的。谁能给个建议?

【问题讨论】:

  • 也许 Misaka 是为处理 unicode 字符串而设计的?

标签: python unicode python-2.7 python-unicode


【解决方案1】:

如果str 总是失败,而unicode 总是成功,你大概需要在传入str 对象之前对其进行解码。诀窍是知道编码:如果你这样做了,你可以这样做(对于例如)a.decode('utf-8')。但如果你不知道,那么我知道 chardet 包可以进行合理的猜测:但请注意,你只能猜测。

【讨论】:

  • 谢谢。 chardet 正是我所需要的。我不知道字符集,所以无法向unicode(text,charset) 提供一个。你拯救了这一天!
猜你喜欢
  • 1970-01-01
  • 2018-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-02
  • 2015-02-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多