在Python中加载文件
我在使用以下代码时遇到一些问题:
with open('townhall.map', 'r') as f:
for line in f:
for character in line:
if character == "x":
print "WALL"
else:
if character == "a":
print "LAND"
else:
print "Unexpected Error loading map!"
townhall.map:
xxxxx
xaaax
xaaax
xaaax
xxxxx
我遇到的问题是它将换行符读取为字符;所以我在输出中得到这个 -
WALL
WALL
WALL
WALL
WALL
Unexpected Error loading map!
WALL
LAND
LAND
LAND
WALL
Unexpected Error loading map!
WALL
LAND
LAND
LAND
WALL
Unexpected Error loading map!
WALL
LAND
LAND
LAND
WALL
Unexpected Error loading map!
WALL
WALL
WALL
WALL
WALL
如何让它忽略换行“字符”?
I'm having some problems with the following code:
with open('townhall.map', 'r') as f:
for line in f:
for character in line:
if character == "x":
print "WALL"
else:
if character == "a":
print "LAND"
else:
print "Unexpected Error loading map!"
townhall.map:
xxxxx
xaaax
xaaax
xaaax
xxxxx
The problem I have is that it reads the newlines as characters; so I get this on output -
WALL
WALL
WALL
WALL
WALL
Unexpected Error loading map!
WALL
LAND
LAND
LAND
WALL
Unexpected Error loading map!
WALL
LAND
LAND
LAND
WALL
Unexpected Error loading map!
WALL
LAND
LAND
LAND
WALL
Unexpected Error loading map!
WALL
WALL
WALL
WALL
WALL
How do I make it ignore newline 'characters'?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
更改此行:
您还可以使 if/else 结构更扁平:
或将打印定义为字典:
Change this line:
And you can also make the if/else structure flatter:
or define the printing as a dictionary:
您还需要考虑换行符,并忽略它。
You need to account for your newline character as well, and ignore it.
有很多方法可以做到这一点。其中之一是:
There are many ways to do that. One of them is: