向空间中添加一个空格的字符串

问题描述:

我正在开发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。每个问题都应该独立,新的解释行不应该与旧的解释行结合。 –

由于堆栈是一个列表,并且您正在调用没有参数的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

您可以更改您的addQuestion以使用整个堆栈。

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

我得到的错误与input,所以我改变了对raw_input。我认为这就是你想要的。

+0

太棒了。这工作。谢谢! –