【问题标题】:What is a robust method for parsing a string that can be used to issue commands什么是解析可用于发出命令的字符串的稳健方法
【发布时间】:2017-02-03 05:45:27
【问题描述】:

我们都使用的某些工具通常允许将字符串解析为可选命令。例如,使用大多数 IRC 工具,可以编写类似 /msg <nick> hi there! 的内容,从而解析字符串并执行命令。

我在周末考虑这个问题,并意识到我完全不知道如何稳健地实现这个功能。我对它的鸟瞰理解是,每个输入都需要被解析,找到用于发出命令的潜在匹配项,并且需要在适当的验证下执行该命令。

我在 Python 中为此写了一个快速的概念证明:

class InputParser:

    def __init__(self):
        self.command_character = '!!'
        self.message = None
        self.command = None
        self.method = None

    def process_message(self, message):
        # every input into the system is sent through here.  If the 
        # start of the string matches the command_character, try and 
        # find the command, otherwise return back the initial
        # message.
        self.message = message

        if self.message.startswith(self.command_character):
            self.command = self.message.split(' ')[0]
            self.method = self.command.replace(self.command_character, '')
            try:
                return self.__class__.__dict__['_%s' % self.method]()
            except KeyError:
                # no matching command found, return the input message 
                return self.message
        return self.message

    def _yell(self):
        # returns an uppercase string
        return self.message.upper().replace(self.command, '')

    def _me(self):
        # returns a string wrapped by * characters
        return ('*%s*' % self.message).replace(self.command, '')

示例用法:

!!yell hello friend > HELLO FRIEND

问题: 有人可以为我提供一个现有项目、现有库的链接,或者给我一个概念性概述,了解一种有效的方法来有效地改变程序解释字符串的方式,从而导致应用程序的不同行为吗?

【问题讨论】:

标签: python string command irc


【解决方案1】:

与其破解类内部结构,不如使用字典将命令字符串映射到执行命令的函数。在类级别设置字典,或者在__init__() 中设置字典(如果实例之间可能不同)。

这样,字典有两个用途:一个是提供有效的命令令牌,另一个是将命令令牌映射到一个动作。

【讨论】:

  • 这基本上就是我所做的。每个commands 都精确映射到类上的一个方法,因此!!yell 映射到def _yell。我正在通过类 dict 访问这些属性。
猜你喜欢
  • 1970-01-01
  • 2018-05-18
  • 1970-01-01
  • 2012-07-28
  • 1970-01-01
  • 1970-01-01
  • 2016-07-30
  • 2011-03-13
  • 1970-01-01
相关资源
最近更新 更多