2011-12-11 72 views
0

我正在開發Python中的迷你語言(不是真的,只是個人項目的一些命令)。向空間中添加一個空格的字符串

下面的代碼:

class FlashCard: 
    def __init__(self): 
     self.commands = {'addQuestion':self.addQuestion} 
     self.stack = [] 
     self.questions = {} 


    def addQuestion(self): 
     question = self.stack.pop() 
     answer = input(question) 


    def interpret(self,expression): 
     for token in expression.split(): 
      if token in self.commands: 
       operator = self.commands[token] 
       operator() 
      else: 
       self.stack.append(token) 

i = FlashCard() 
i.interpret('testing this addQuestion') 

的解釋功能只拉字符串中的最後一個字(這一點)。有沒有辦法讓它拉動整條線?

謝謝!

+1

從即將到來的答案,即時混淆你真正想要的結果。您是否試圖保留傳遞給解釋的整個表達式或僅保留不是命令令牌的標記?另外,如果在表達式中間找到一個命令標記,那麼它將被調用,並且只對在它之前被捕獲的標記起作用。這也是你想要的嗎? – jdi

+1

@jdi - 只有OP知道肯定,但從代碼我會期望他正在建立一個自定義命令的解析器,如「什麼是貓」的土耳其語翻譯? addQuestion' [這可能會添加一個新的閃存卡,問題是:「什麼是土耳其語翻譯」貓「?」雖然我可能是錯的! :) – mac

+0

你是對的,mac。每個問題都應該獨立,新的解釋行不應該與舊的解釋行結合。 –

回答

2

由於堆棧是一個列表,並且您正在調用沒有參數的pop方法,您將得到的是列表中的最後一個元素。你可能想變換一個空間分隔的字符串列表,而不是:

def addQuestion(self): 
    question = ' '.join(self.stack) 
    answer = input(question) 

觀察到的popjoin的副作用是不同的。 pop將修改原始列表:

>>> stack = ['testing', 'this'] 
>>> stack.pop() 
'this' 
>>> stack 
['testing'] 

join不會:

>>> stack = ['testing', 'this'] 
>>> ' '.join(stack) 
'testing this' 
>>> stack 
['testing', 'this'] 

編輯(見下面的OP的評論):要在同一解析多行/命令輸入,你可以做不同的事情。這使我想到的最簡單的:沖洗後調用堆棧operator()

if token in self.commands: 
    operator = self.commands[token] 
    operator() 
    self.stack = [] 

編輯2(見下面我自己的評論):下面是使用字符串列表完整的示例:

class FlashCard: 
    def __init__(self): 
     self.commands = {'addQuestion':self.addQuestion} 

    def addQuestion(self, phrase): 
     answer = raw_input(phrase) 

    def interpret(self, expressions): 
     for expression in expressions.split('\n'): 
      phrase, command = expression.rsplit(' ', 1) 
      if command in self.commands: 
       operator = self.commands[command] 
       operator(phrase) 
      else: 
       raise RuntimeError('Invalid command') 

expressions = '''testing this addQuestion 
testing that addQuestion 
testing error removeQuestion''' 
i = FlashCard() 
i.interpret(expressions) 

HTH!

+0

你搖滾!謝謝。 :) –

+0

問題是它不會是完整的行,因爲它不會追加匹配的命令標記。它唯一附加的詞不匹配命令。似乎他想追加所有的令牌......捕獲命令令牌......並在末尾調用它 – jdi

+0

@jdi - 如果我理解OP想要做什麼,那應該是正確的行爲,但我可能是雖然錯了! :) – mac

1

您可以更改您的addQuestion以使用整個堆棧。

def addQuestion(self): 
    question = ' '.join(self.stack) + '?' 
    self.stack = [] 
    answer = raw_input(question) 

我得到的錯誤與input,所以我改變了對raw_input。我認爲這就是你想要的。

+0

太棒了。這工作。謝謝! –