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すると、西に設定されます。userInput代わりに正規表現を使用するtextArrayと、メソッドがmovementnull のままになります。

編集 コードをさらにテストして変更した後、正規表現は問題なく、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 に答える
1

コードを修正しました。ブロック内のタイプミス&の代わりにif string == 'South':使用する必要がありますanalysetextarray

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 に答える