为了练习正则表达式,我正在尝试创建一个类似于Zork的非常简单的基于文本的游戏。但是我似乎无法使用正则表达式来执行代码。
运动
import re
def userMove():
userInput = raw_input('Which direction do you want to move?')
textArray = userInput.split()
analyse = [v for v in textArray if re.search('north|east|south|west|^[NESW]', v, re.IGNORECASE)]
print textArray
print analyse
movement = 'null'
for string in analyse:
if string is 'North' or 'n':
movement = 'North'
elif string is 'East'or'e':
movement = 'East'
elif string is 'South'or's':
movement = 'South'
elif string is 'West'or'w':
movement = 'West'
print movement
if / elif样品运行
>>> import movement
>>> moves = movement.userMove()
Which direction do you want to move?Lets walk East
['Lets', 'walk', 'East']
['East']
North
如果样品运行
>>> import movement
>>> moves = movement.userMove()
Which direction do you want to move?I`ll run North
['I`ll', 'run', 'North']
['North']
West
如果for
循环将不断设置movement
为北;并使用if
而不是语句elif
将其设置为West。使用正则表达式userInput
代替textArray
导致方法保持movement
为null。
编辑在进一步测试和更改代码之后,我确定正则表达式很好,并且这是if
语句或for
循环的错误。
您的问题在于以下if
语句:
if string is 'North' or 'n':
movement = 'North'
elif string is 'East'or'e':
movement = 'East'
elif string is 'South'or's':
movement = 'South'
etc...
它们与您的期望不符。首先,您不应该将字符串与is
-进行比较==
。其次,该语句的评估方式如下:
if (string is 'North') or 'n':
movement = 'North'
因此,'n'
始终True
-意味着您的movement
变量始终设置为North
。
尝试以下方法:
if string in ('North', 'n'):
etc...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句