为了练习正则表达式,我正在尝试创建一个类似于Zork的非常简单的基于文本的游戏。但是我似乎无法使用正则表达式来运行代码。
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
if / elif Sample Run
>>> 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
循环的错误。
答案 0 :(得分:3)
您的问题出在这些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...
答案 1 :(得分:2)
错字:
elif string == 'South':
movement == 'South'
print 'Go South'
替换==与=
答案 2 :(得分:1)
更正后的代码。 if string == 'South':
块中的错字&您应该使用analyse
代替textarray
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('[N|n]orth|[E|e]ast|[S|s]outh|[W|w]est', v)]
print analyse
movement = 'null'
for string in analyse:
if string == 'North':
movement = 'North'
print 'Go North'
elif string == 'East':
movement = 'East'
print 'Go East'
elif string == 'South':
movement = 'South'
print 'Go South'
elif string == 'West':
movement = 'West'
print'Go West'
return movement