【问题标题】:Is there a Python library for custom autocompletion?是否有用于自定义自动完成的 Python 库?
【发布时间】:2011-10-14 05:27:27
【问题描述】:

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

这是我正在寻找的示例。

语法:

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

项目:

  • 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

【问题讨论】:

  • @S.Lott - 您标记为“完全重复”的问题 - 虽然相关 - 它不是重复的。该问题仅涉及根据其他字符串列表完成字符串。我的问题是关于定义语法规则,然后在此基础上进行自动完成。 :)
  • 更新您的问题,以明确您的问题与其他看似相同的问题有何不同。您可能希望搜索所有其他 Python 自动完成问题并找出与所有先前问题的具体差异。

标签: python parsing user-interface autocomplete grammar


【解决方案1】:

我知道的一个自动完成模块是 Qt 的 QCompleter,您可以通过 PyQt 或 PySide 在 Python 中使用它。我不认为它以您的意思理解语法,但它足够通用,可以让您编写可以理解的代码。

【讨论】:

    【解决方案2】:

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

    关于 SPARK

    SPARK 代表扫描、解析和重写工具包。它以前 没有名字,被称为“小语言框架”。 第一个版本(大约 1998 年)在第 7 届国际 Python 会议上的论文Compiling Little Languages in Python 中进行了描述。

    SPARK 是用 100% 纯 Python 编写的,并且以开放的形式提供 来源。

    自动完成代码

    在以下代码中:

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

    这里是相关代码sn-ps:

    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)
    

    【讨论】:

      猜你喜欢
      • 2018-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-24
      • 2023-03-16
      • 2012-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多