2013-11-03 107 views
1

要练习正则表达式,我试图创建一个类似于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循环的错误。

+2

正则表达式,即'analyse'的结果,是从来没有在程序的任何地方使用? – poke

+0

对不起,我上传了一个我正在编辑的文件来尝试解决问题,而不是错误的实际文件。现在(有固定的拼写错误),如果输入没有被接受的字符串,代码将返回null,但是如果它是一个是 –

回答

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... 
+0

谢谢你这样明确的答案 –

+0

没问题!我很惊讶没有人在我面前指出过。 – Ben

2

错字在:

elif string == 'South': 
    movement == 'South' 
    print 'Go South' 

与=

+0

,那么它总是为北向感谢您指出这一点 –

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