【发布时间】:2014-01-27 20:55:36
【问题描述】:
我认为我对非 ascii 的字符集从根本上感到困惑。
我有一个 python 文件,我在顶部声明为# -*- coding: cp1252 -*-。
例如,在文件中我有question = "what is your borther’s name"。
type(question)
>> 字符串
question
>> '你的兄弟叫什么\xe2\x80\x99s'
此时我无法转换为 unicode,大概是因为您无法从 ASCII 转换为 Unicode。
UnicodeDecodeError:“ascii”编解码器无法解码位置 20 中的字节 0xe2:序数不在范围内 (128)
如果我以 unicode 开头:
question = "what is your borther’s name"
>>你'你的兄弟叫什么名字'
如何找回“你哥哥叫什么名字”?或者只是 python 解释器显示 unicode 字符串的方式,当我将它传递给支持 unicode 的应用程序(在本例中为 Office)时,它实际上会正确编码?
我需要保留特殊字符,但我仍然需要使用 Levenshtein 库 (pip install python-Levenshtein) 进行字符串比较。
Levenshtein.ratio 的两个参数都采用 str 或 unicode,但不能混合使用。
【问题讨论】:
-
unicode(mystring.decode("cp1252")),行得通吗?
-
不,似乎一旦字符串为 ascii,它就不会转换回 unicode。见我上面的编辑。
标签: python unicode encoding ms-office cp1252