0

我正在使用 Python 3.2.3 和空闲来编写文本游戏。我正在使用 .txt 文件来存储稍后将由程序打开并在终端上绘制的地图方案(暂时空闲)。

.txt 文件中的内容是:

╔════Π═╗
Π      ║ 
║w bb c□
║w bb c║ 
╚═□══□═╝

Π:门;□:窗;b:床;c:电脑;w: 衣柜

由于我是编程新手,因此我在执行此操作时遇到了难题。

这是我到目前为止为此编写的代码:

doc =  codecs.open("D:\Escritório\Codes\maps.txt")
map = doc.read().decode('utf8')
whereIsmap = map.find('bedroom')
if buldIntel == 1 and localIntel == 1:
    whereIsmap = text.find('map1:')
    itsGlobal = 1
if espLocation == "localIntel" == 1:
    whereIsmap = text.find('map0:')
if buldIntel == 0 and localIntel == 0:
    doc.close()

for line in whereIsmap:
    (map) = line
    mapa.append(str(map))
doc.close()

if itsGlobal == 1:
    print(mapa[0])
    print(mapa[1])
    print(mapa[2])
    print(mapa[3])
    print(mapa[4])
    print(mapa[5])
    print(mapa[6])
    print(mapa[7])

if itsLocal == 1 and itsGlobal == 0:
    print(mapa[0])
    print(mapa[1])
    print(mapa[2])
    print(mapa[3])
    print(mapa[4])

有两张地图,每一张都有一个标题,较小的一张是 map1(我展示的那个)。

如果我尝试运行程序,Python 会给出此错误消息:

Traceback (most recent call last):
  File "C:\Python32\projetoo", line 154, in <module>
    gamePlay(ask1, type, selfIntel1, localIntel, buildIntel, whereAmI, HP, time, itsLocal, itsBuild)
  File "C:\Python32\projetoo", line 72, in gamePlay
    map = doc.read().decode('utf8')
  File "C:\Python32\lib\encodings\utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

我该怎么做才能将地图完全按照我在那里显示的方式打印到 IDLE 终端?

4

1 回答 1

2

问题是您使用codecs.open时没有指定编码,然后尝试解码由返回的字符串doc.read(),即使它已经是 Unicode 字符串。

codecs.open要解决此问题,请在对:的调用中指定编码codecs.open("...", encoding="utf-8"),这样以后就不需要调用了.decode('utf-8')

此外,由于您使用的是 Python 3,因此您可以使用open

doc = open("...", encoding="utf-8").read()

最后,您需要在打印时重新编码 unicode 字符串:

print("\n".join(mapa[0:4]).encode("utf-8"))
于 2012-06-06T18:25:39.493 回答