【发布时间】: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
问题: 有人可以为我提供一个现有项目、现有库的链接,或者给我一个概念性概述,了解一种有效的方法来有效地改变程序解释字符串的方式,从而导致应用程序的不同行为吗?
【问题讨论】:
-
听起来你需要一个词法分析器/字符串标记器。试试stackoverflow.com/q/36953/1141876