Skip to main content
 首页 » 编程设计

Python 2.7 和正则表达式 : False if statement returns

2025年05月04日24tuyile006

为了练习正则表达式,我正在尝试创建一个非常简单的基于文本的游戏,类似于 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 设置为 North;并使用 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...