要练习正则表达式,我试图创建一个类似于Zork的非常简单的基于文本的游戏。然而,我似乎无法使用正则表达式的代码工作。Python 2.7&正则表达式:如果语句返回,则为False
Movement.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
如果/ 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
循环的错误。
正则表达式,即'analyse'的结果,是从来没有在程序的任何地方使用? – poke
对不起,我上传了一个我正在编辑的文件来尝试解决问题,而不是错误的实际文件。现在(有固定的拼写错误),如果输入没有被接受的字符串,代码将返回null,但是如果它是一个是 –