Пример с выводом результата в консоль.
import sys
import unicodedata
def print_unicode_table(word):
print("decimal hex chr {0:^40}".format("name"))
print("------- ----- --- {0:-<40}".format(""))
code = ord(" ")
end = sys.maxunicode
while code < end:
c = chr(code)
name = unicodedata.name(c, "*** unknown ***")
if word is None or word in name.lower():
print("{0:7} {0:5X} {0:^3c} {1}".format(code, name.title()))
code += 1
word = None
if len(sys.argv) > 1:
if sys.argv[1] in ("-h", "--help"):
print("usage: {0} [string]".format(sys.argv[0]))
word = 0
else:
word = sys.argv[1].lower()
if word != 0:
print_unicode_table(word)
Traceback (most recent call last):При этом есть пример с выводом в текстовый файл:
File “C:\Python31\print_unicode.py”, line 26, in <module>
print_unicode_table(word)
File “C:\Python31\print_unicode.py”, line 15, in print_unicode_table
print(“{0:7} {0:5X} {0:^3c} {1}”.format(code, name.title()))
File “C:\Python31\lib\encodings\cp866.py”, line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_map)
UnicodeEncodeError: ‘charmap’ codec can't encode character ‘\xa1’ in position 15
: character maps to <undefined>
import sys
import unicodedata
def print_unicode_table(word):
filename = "unicode-table.txt"
fh = open(filename, "w", encoding="utf8")
fh.write("decimal hex chr {0:^40}\n".format("name"))
fh.write("------- ----- --- {0:-<40}\n".format(""))
code = ord(" ")
end = min(0xD800, sys.maxunicode) # Stop at surrogate pairs
while code < end:
c = chr(code)
name = unicodedata.name(c, "*** unknown ***")
if word is None or word in name.lower():
fh.write("{0:7} {0:5X} {0:^3c} {1}\n".format(
code, name.title()))
code += 1
print("wrote results to", filename)
word = None
if len(sys.argv) > 1:
if sys.argv[1] in ("-h", "--help"):
print("usage: {0} [string]".format(sys.argv[0]))
word = 0
else:
word = sys.argv[1].lower()
if word != 0:
print_unicode_table(word)
Не могу понять в чем причина ошибки с выводом на консоль и как ее избежать.