您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在python中编写自动补全代码?

如何在python中编写自动补全代码?

(我知道这并不是您所要的,但是)如果您对自动TAB补全/建议(如许多shell中使用的)所出现的情况感到满意,则可以使用以下命令快速启动并运行在readline的模块。

这是一个基于Doug Hellmann在readline的PyMOTW编写快速示例。

import readline

class MyCompleter(object):  # Custom completer

    def __init__(self, options):
        self.options = sorted(options)

    def complete(self, text, state):
        if state == 0:  # on first trigger, build possible matches
            if text:  # cache matches (entries that start with entered text)
                self.matches = [s for s in self.options 
                                    if s and s.startswith(text)]
            else:  # no text entered, all matches possible
                self.matches = self.options[:]

        # return match indexed by state
        try: 
            return self.matches[state]
        except IndexError:
            return None

completer = MyCompleter(["hello", "hi", "how are you", "goodbye", "great"])
readline.set_completer(completer.complete)
readline.parse_and_bind('tab: complete')

input = raw_input("Input: ")
print "You entered", input

这将导致以下行为(<TAB>表示按下了Tab键):

Input: <TAB><TAB>
goodbye      great        hello        hi           how are you

Input: h<TAB><TAB>
hello        hi           how are you

Input: ho<TAB>ow are you

在最后一行(H``O``TAB输入的)中,只有一个可能的匹配项,并且整个句子“你好吗”是自动完成的。

请查看链接文章,以获取有关的更多信息readline

“更好的情况是,它不仅可以从头开始完成单词,而且可以从字符串的任意部分完成单词。”

这可以通过在完成函数中简单地修改匹配条件来实现。从:

self.matches = [s for s in self.options 
                   if s and s.startswith(text)]

像这样:

self.matches = [s for s in self.options 
                   if text in s]

这将为您提供以下行为:

Input: <TAB><TAB>
goodbye      great        hello        hi           how are you

Input: o<TAB><TAB>
goodbye      hello        how are you
python 2022/1/1 18:31:40 有200人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶