我正在使用Python 3.2.3和空闲来编程文本游戏。我正在使用一个.txt文件来存储地图方案,稍后将由程序打开并在终端绘制(暂时处于空闲状态)。
.txt文件中的内容是:
╔════Π═╗
Π ║
║w bb c□
║w bb c║
╚═□══□═╝
Π:门;□:窗户;b:床;c:电脑;w:衣柜
由于我是编程新手,因此在执行此操作时遇到了一个难题。
这是我到目前为止为此编写的代码:
doc = codecs.open("D:EscritórioCodesmaps.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:Python32projetoo", line 154, in <module>
gamePlay(ask1, type, selfIntel1, localIntel, buildIntel, whereAmI, HP, time, itsLocal, itsBuild)
File "C:Python32projetoo", line 72, in gamePlay
map = doc.read().decode('utf8')
File "C:Python32libencodingsutf_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终端,就像我在那里显示的那样?
问题是您在没有指定编码的情况下使用 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"))