【问题标题】:python unicode woes - convert cp1252 string to unicodepython unicode woes - 将 cp1252 字符串转换为 unicode
【发布时间】: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


【解决方案1】:

我有一个纯文本文件,我在顶部声明为# -*- coding: cp1252 -*-

这没什么。

with codecs.open(..., encoding='cp1252') as fp:
   ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-30
    • 2011-05-07
    • 1970-01-01
    相关资源
    最近更新 更多