"返回codecs.charmap_encode"当运行没有异常字符的python脚本时

时间:2014-05-08 20:01:22

标签: python windows encoding cmd python-idle

我正在尝试在CMD中运行我的脚本(它在IDLE中工作正常),但是我收到了这个错误:

C:\Python34>rule90.py Traceback (most recent call last): File "C:\Python34\rule90.py", line 15, in <module> print(c) File "C:\Python34\lib\encodings\cp850.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-39: character maps to <undefined>

虽然我对python的经验有限,但我认为我已经足够了解这个。第19行只是linenew = str(''.join(lineA[numberneg:numberpos])),我加入的lineA包含字符串形式的'0'和'1'的加载。我有■和□字符,但它们应该是cmd中的默认字符,并且错误不在该行上。

任何帮助将不胜感激!

lineA = ['0','0','0','0','0','0','1','0','0','0','0','0','0']
lineB = lineA[:]
lineC = lineA[:]
lineC = ['□' if x=='0' else '■' for x in lineC]
counth = 0
max_counth = len(lineA) - 2
countv = 0
max_countv = len(lineA) / 2 - 1

while countv < max_countv:
    number = 1
    counth = 0
    lineCstr = map(str, lineC)    
    c = ''.join(lineCstr)
    print(c)
    while counth < max_counth:
        numberneg = number - 1
        numberpos = number + 2
        linenew = str(''.join(lineA[numberneg:numberpos]))
        if linenew == str('110') or linenew == str('100') or linenew == str('011') or linenew == str('001'):
            lineB[number] = '1'
            lineC[number] = '■'
        else:
            lineB[number] = '0'
            lineC[number] = '□'
        number = number + 1
        counth = counth + 1

    lineA = lineB[:]
    countv = countv + 1
input("Press Enter to continue...")

lineA通常是一个较长的列表(25个以上的数字),但为了节省空间我缩短了它。

1 个答案:

答案 0 :(得分:0)

我可以做出一个假设。目前,符号'□'和'■'都是Unicode的符号。您可以像这样得到它的十六进制代码:

import binascii
print (binascii.hexlify(bytes('□','UTF-8'))) #b'e296a1'
print (binascii.hexlify(bytes('■','UTF-8'))) #b'e296a0'

您可以找到Unicode表格here。 由于某种原因,您的控制台无法显示Unicode字符。但是你可以在控制台编码中找到它们的等价物:

for i in range(256):
    print (i,chr(i))

请记住每个方格i的值。然后你可以这样做:

BLACK_SQUARE = ord(some_integer_value)
WHITE_SQUARE = ord(some_integer_value)

lineC = [WHITE_SQUARE if x=='0' else BLACK_SQUARE  for x in lineC]