python - 一个足够的 MUD 风格和适用于 Python 的文本解析器的例子

标签 python algorithm parsing text

我正在编写一个类似MUD的游戏,更多的是为了体验和练习。我正在尝试找到一种可以有效地执行文本命令的算法。如果你在知道我在说什么之前玩过 MUD 类型的游戏。如果没有,例如,如果我输入命令:“搜索”,无论您输入 s、se、sea、sear、searc、search 等,它都会执行“搜索”...

现在我确实已经建立了一个算法,但是我越想越发现出现的问题。在代码中它是这样的:

 def text_parser(string, command):
    string_list = []
    command_list = []

    for x in string:
        string_list.append(x)

    for x in command:
        command_list.append(x)

    if len(string_list) == 0:     # checks to see if user have entered anything
        return False

    if ((string_list > command_list) - (string_list < command_list)) is 1:    # returns false if string has more items than command
        return False

    else:
        if string_list[:len(string_list)] == command_list[:len(string_list)]:
            return True
        else:
            return False

您可以通过以下方式调用此函数:

if text_parser('hel', 'hello') is True:
    print('This returns True')

if text_parser('hel', 'Foo') is True:
    print('This returns False')

现在这段代码可以完美地工作.. 正是我需要它做的。如果我为命令“搜索”输入“se”及其其他最终成员,它将始终为真......但现在我最大的问题来了......假设我有两个命令:

'quit' 和 'quaff' 并且用户只输入 'qu'

根据我的算法,它会同时执行'quit' 和'quaff',因为我的代码设置为:

if (text parser check):
    blah
if (text parser check):
    blach
etc....   # The only way out of this is to do nested if's and elif's.. which will look messy..

这根本不是我想做的。如您所见,您在游戏中设置的命令越多,问题就会越多。

什么是文本解析的好算法?还是我只需要更改现有代码中的一些内容来解决此设置可能会出现的错误...?谢谢

最佳答案

我认为您的方法可以通过列出所有可用命令来简化。然后定义一个函数来解析您的输入字符串并查找这样的命令匹配:

all_commands = ['search', 'quit', 'quaff']

def find_command(string, allowed_commands=None):
    if allowed_commands is None:
        # if there is no restrictions, look for all commands
        allowed_commands = all_commands

    matching_commands = []

    for command in commands:
        if command.startswith(string):
            matching_commands.append(command)

    if len(matching_commands) == 1:
        # found a match
        return matching_commands[0]

    # found either no match or more than one
    return None

现在,函数 find_command 将为输入的 string 找到匹配项,它将匹配所有命令 (all_commands) 或给定的子集(allowed_commands),以防您只想在那种情况下允许某些命令。

例如:

print find_command('se') # returns search
print find_command('search') # returns search
print find_command('qu') # returns None
print find_command('quaf') # returns quaff
print find_command('qu', ['search', 'quit']) # returns quit

关于python - 一个足够的 MUD 风格和适用于 Python 的文本解析器的例子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27610924/

相关文章:

android getElementsByTagName 返回空列表

Python :Wave. 将帧读取到 numpy 数组以获取 fft

python - IronPython 奇怪的行为

python - 在蛇中用图像替换立方体

algorithm - 选择一组对以最小化组的均方根

PHP DOM 解析所有文本节点

python - 将 pandas DataFrame 存储在 PyTables 表中而不存储索引

java - 将二叉树转换为仅包含叶节点的链表

algorithm - 在流网络的所有最小切割中找到最少的边缘

java - 地址解析