Unicode无法正确打印到cp850(cp437),扑克牌套装
作者:互联网
总结一下:如何独立打印unicode系统以产生纸牌符号?
我做错了什么,我认为自己在Python方面很流利,但我似乎无法正确打印!
# coding: utf-8
from __future__ import print_function
from __future__ import unicode_literals
import sys
symbols = ('♥','♦','♠','♣')
# red suits to sdterr for IDLE
print(' '.join(symbols[:2]), file=sys.stderr)
print(' '.join(symbols[2:]))
sys.stdout.write(symbols) # also correct in IDLE
print(' '.join(symbols))
打印到控制台是控制台应用程序的主要考虑因素,但不幸地失败了:
J:\test>chcp
Aktiivinen koodisivu: 850
J:\test>symbol2
Traceback (most recent call last):
File "J:\test\symbol2.py", line 9, in <module>
print(''.join(symbols))
File "J:\Python26\lib\encodings\cp850.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-3: character maps to <unde
fined>
J:\test>chcp 437
Aktiivinen koodisivu: 437
J:\test>d:\Python27\python.exe symbol2.py
Traceback (most recent call last):
File "symbol2.py", line 6, in <module>
print(' '.join(symbols))
File "d:\Python27\lib\encodings\cp437.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\u2660' in position 0: character maps
o <undefined>
J:\test>
因此,总之,我有一个控制台应用程序,只要您不使用控制台,而是IDLE,它就可以正常工作.
我当然可以通过chr生成它们自己生成符号:
# correct symbols for cp850
print(''.join(chr(n) for n in range(3,3+4)))
但这看起来很愚蠢.而且我不会使程序仅在Windows上运行或有很多特殊情况(例如条件编译).我想要可读的代码.
我不介意它输出的字母,只要它看起来是正确的,无论是诺基亚电话,Windows还是Linux. Unicode应该可以,但是不能正确打印到控制台
解决方法:
使用Unicode字符串和编解码器模块:
要么:
# coding: utf-8
from __future__ import print_function
import sys
import codecs
symbols = (u'♠',u'♥',u'♦',u'♣')
print(u' '.join(symbols))
print(*symbols)
with codecs.open('test.txt','w','utf-8') as testfile:
print(*symbols, file=testfile)
要么:
# coding: utf-8
from __future__ import print_function
from __future__ import unicode_literals
import sys
import codecs
symbols = ('♠','♥','♦','♣')
print(' '.join(symbols))
print(*symbols)
with codecs.open('test.txt','w','utf-8') as testfile:
print(*symbols, file=testfile)
无需重新执行打印.
标签:cmd,windows-xp,python 来源: https://codeday.me/bug/20191105/1996723.html