【问题标题】:How to print german diacritic characters in Python 2.7?如何在 Python 2.7 中打印德语变音符号?
【发布时间】:2012-12-20 01:41:50
【问题描述】:

在 Excel2007 电子表格(我使用 xlrd xlwt 和 openpyxl)中处理德语单词(有时包含变音符号),我得到以下值:

var = str(ws.cell(row=i+k,column=0).value).encode('latin-1')

我得到了 print(var):

'[a word')

直到出现一个包含元音变音字符的单词,当我得到:

Traceback (most recent call last):
  File "C:\Users\cristina\Documents\horia\Linguistics3\px t3.py", line 68, in <module>
    var = str(ws4.cell(row=i+k,column=0).value).encode('latin-1')
UnicodeEncodeError: 'ascii' codec can't encode character u'\xdf' in position 3:ordinal not in range(128)

然后程序停止。

如果我将 var 定义为:

var = u'str(ws4.cell(row=i+k,column=0).value)'.encode('latin-1')

我明白了,当母鸡尝试打印(var)时,我明白了:

var=str(ws.cell(row=i+k,column=0).value)

程序正常运行到结束

我可以在 Python Shell 中获取 var 的值,但不能通过程序中的“print(var)”获取。

谁能给我一个解决方案?

【问题讨论】:

  • 尝试使用 .encode('utf-8') 或 .encode('latin1', 'ignore')...
  • print ws4.cell(row=i+k,column=0).value.encode('latin-1') 可能吗?
  • @Hedde,不,那不是重复的

标签: python encoding character diacritics


【解决方案1】:

首先,请阅读:http://www.joelonsoftware.com/articles/Unicode.html(认真)

然后,了解 Python2 有两种不同的数据类型: unicode,用于“不可知”处理所有可能的字符,但不能用于 输入/输出,例如“打印”或写入文件,而不被编码到 其他数据类型:字符串。

字符串依赖于编码。

鉴于您的错误消息,我几乎可以肯定的是,ws4.cell(row=i+k,column=0).value 调用正在返回一个 unicode 值。 (我不能在这里在我的非 Windows 环境中测试它) - 为了确保不是猜测工作,你可能想在那里运行一次 print (type(ws4.cell(row=i+k,column=0).value) 只是为了断言您正在获取 unicode 值。

因此,当您执行 str(ws4.(...).value) 时,您是在告诉 Python 将 unicode 转换为 str 而不进行任何编码 - 这是引发错误的调用,而不是随后的“解码”调用。

如果发生这种情况,只需将 str 调用替换为 unicode

var = u'str(ws4.cell(row=i+k,column=0).value)'.encode('latin-1') 

这应该可以解决您的问题。我希望您已经阅读了我在上面链接的文章 - 它有帮助的。

另外,用您正在使用的相应编码标记您的 Python 源代码 - 否则 您的源代码中的任何非 ASCII 字符都会出错。

例如,在代码的第一行写下:

# coding: latin1

(尽管对于任何严肃的项目,您都应该使用 utf-8。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 2016-01-21
    • 2011-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多