python-2.7 - Python : ascii codec can't encode en-dash

标签 python-2.7 printing utf-8 non-ascii-characters utf8-decode

我正在尝试使用支持 CP437 编码的 thermal printer 从诗歌基金会的每日诗歌 RSS 提要中打印一首诗。这意味着我需要翻译一些字符;在这种情况下,连字符的短划线。但是 python 甚至不会编码开始的破折号。当我尝试解码字符串并用连字符替换破折号时,出现以下错误:

Traceback (most recent call last):
  File "pftest.py", line 46, in <module>
    str = str.decode('utf-8')
  File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 140: ordinal not in range(128)

这是我的代码:
#!/usr/bin/python
#-*- coding: utf-8 -*-

# This string is actually a variable entitled d['entries'][1].summary_detail.value
str = """Love brought by night a vision to my bed,
One that still wore the vesture of a child
But eighteen years of age – who sweetly smiled"""

str = str.decode('utf-8')
str = str.replace("\u2013", "-") #en dash
str = str.replace("\u2014", "--") #em dash
print (str)

我实际上可以在终端窗口 (Mac) 中使用以下代码打印输出而不会出错,但我的打印机会吐出 3 个 CP437 字符集:
str = u''.str.encode('utf-8')

我使用 Sublime Text 作为我的编辑器,并且我用 UTF-8 编码保存了页面,但我不确定这会有所帮助。我将不胜感激任何有关此代码的帮助。谢谢!

最佳答案

我不完全了解您的代码中正在发生的情况,但是我也一直尝试用连字符代替连字符,这些字符是从Web上获得的字符串,这对我有用。我的代码就是这样:

txt = re.sub(u"\u2013", "-", txt)

我正在使用 Python 2.7 和 Sublime Text 2,但我不想在我的脚本中设置 -*- coding: utf-8 -*-,因为我试图不引入任何新的编码问题。 (即使我的变量可能包含Unicode,我也希望将代码保持为纯ASCII。)是否需要在.py文件中包括Unicode,还是只是为了帮助调试?

我会注意到我的 txt 变量已经是一个 unicode 字符串,即
print type(txt)

产生
<type 'unicode'>

我很想知道 type(str) 在你的情况下会产生什么。

我在你的代码中注意到的一件事是
str = str.replace("\u2013", "-") #en dash

你确定这有什么作用吗?我的理解是 \u 仅表示 u"" 字符串中的“unicode 字符”,而您创建的字符串包含 5 个字符、“u”、“2”、“0”等(第一个字符是因为您可以转义任何字符,如果没有特殊含义,例如 '\n' 或 '\t',它只会忽略反斜杠。)

此外,您从打印机获得 3 个 CP437 字符这一事实让我怀疑您的字符串中仍然有破折号。 en-dash 的 UTF-8 编码是 3 个字节: 0xe2 0x80 0x93 。当您在包含短划线的 unicode 字符串上调用 str.encode('utf-8') 时,您会在返回的字符串中获得这三个字节。我猜你的终端知道如何将它解释为一个破折号,这就是你所看到的。

如果你不能让我的第一种方法起作用,我会提到我也成功了:
txt = txt.encode('utf-8')
txt = re.sub("\xe2\x80\x93", "-", txt)

如果你把它放在你调用 re.sub() 之后,那么 encode() 可能对你有用。在这种情况下,您甚至可能根本不需要对 decode() 的调用。我承认我真的不明白为什么它在那里。

关于python-2.7 - Python : ascii codec can't encode en-dash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33307690/

相关文章:

python - Python 登录机器人遇到问题

html - 如何从 TDBGrid 打印或查看 HTML?

algorithm - 反函数算法Excel

mysql - 导入到 mySQL 后 UTF-8 字符显示不同

Mysql 四字节汉字支持

python - 使用 BeautifulSoup 调用特定的 'div' 元素

python - 在 Python 2.7 中表示 µs

c - Win32 PrintDlg、PrintDlgEx、崩溃和怪异

utf-8 - 如何将ansi文本转换为utf8

python - 如何运行仅在 Pandas 中选择第一次出现的条件查询?