是否有用于自定义自动完成的Python库?

2024-10-02 12:31:25 发布

您现在位置:Python中文网/ 问答频道 /正文

是否有一个通用库,允许我根据自定义语法和项目列表进行自动完成?

这是我要找的一个例子。在

语法:

  • 你可以大嚼苹果和芒果
  • 你可以喝牛奶和水
  • 你可以移动任何东西
  • 句子结构:动词[+形容词]+宾语

项目:

  • 绿苹果1
  • 1个小苹果
  • 1个绿芒果
  • 1个黄芒果
  • 1个芒果[没有颜色]
  • 1牛奶
  • 1水

预期行为(第一行是用户的输入,第二行是建议)

m
move, munch

mo
move

move g
move green apple, move green mango

move y
move yellow mango

move m
move milk, move mango, move microscopic apple

Tags: 项目苹果apple列表move语法动词green
2条回答

我最终找到了一个可接受的解决方案,它使用了SPARK(用于语法分析/语法分析)和我自己的自动完成代码。在

关于SPARK

SPARK stands for the Scanning, Parsing, and Rewriting Kit. It formerly had no name, and was referred to as the "little language framework." The first version (circa 1998) was described in the paper Compiling Little Languages in Python at the 7th International Python Conference.

SPARK is written in 100% pure Python, and is made available as open source.

自动完成代码

在以下代码中:

  • category是我们正在自动完成的单词。这是通过解析当前命令行获得的。例如:如果用户输入的是“drink m”,解析器将知道语法中定义的类别为“liquids”的单词。在
  • 用户输入存储在列表中(self.chars
  • _get_list_of_existing()返回给定类别中现有单词的列表
  • _get_common_beginning()返回-如果可用-多个匹配项的最长初始超序列。例如,如果用户输入正在写入“ma”,并且可能的自动补全单词是[magnolia,magnaling glass],则_get_common_beginning()将返回“magn”。在

以下是相关代码片段:

def autocomplete(self, category):
    '''
    If possible, autocomplete a word according to its category.
    '''
    root = ''.join(self.chars).split()[-1]  #The bit after the last space
    pool = self._get_list_of_existing(category)
    matches = [i for i in pool if i.find(root) == 0]
    if len(matches) == 1:
        match = matches[0]+' '
    elif len(matches) > 1:
        match = self._get_common_beginning(matches)
    else:
        return
    self.chars.extend(list(match[len(root):]))

def _get_common_beginning(self, strings):
    '''
    Return the strings that is common to the beginning of each string in
    the strings list.
    '''
    result = []
    limit = min([len(s) for s in strings])
    for i in range(limit):
        chs = set([s[i] for s in strings])
        if len(chs) == 1:
            result.append(chs.pop())
        else:
            break
    return ''.join(result)

我知道的一个自动完成模块是Qt的QCompleter,可以通过PyQt或PySide在Python中使用它。我不认为它能像你所说的那样理解语法,但它的通用性足以让你编写这样的代码。在

相关问题 更多 >

    热门问题