为了练习正则表达式,我正在尝试创建一个非常简单的基于文本的游戏,类似于 Zork。但是,我似乎无法使用正则表达式使代码工作。
运动.py
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
为空。
编辑
在进一步测试和更改代码后,我确信正则表达式很好,它是if
语句或for
循环的错误。