1

为了练习正则表达式,我正在尝试创建一个非常简单的基于文本的游戏,类似于 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循环的错误。

4

3 回答 3

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...
于 2013-11-03T21:35:44.403 回答
2

输入错误:

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

将 == 替换为 =

于 2013-11-03T18:51:30.030 回答
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
于 2013-11-03T18:59:09.587 回答