栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

(我知道这并不是您所要的,但是)如果您对自动

TAB
补全/建议(如许多shell中使用的)所出现的情况感到满意,则可以使用以下命令快速启动并运行在readline的模块。

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

import readlineclass 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 Nonecompleter = 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        hihow are youInput: h<TAB><TAB>hello        hihow are youInput: 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        hihow are youInput: o<TAB><TAB>goodbye      hello        how are you

更新:使用历史记录缓冲区(如注释中所述)

创建用于滚动/搜索的伪菜单的简单方法是将关键字加载到历史记录缓冲区中。然后,您将可以使用向上/向下箭头键滚动浏览条目,也可以使用

Ctrl
+
R
进行反向搜索。

要尝试此操作,请进行以下更改:

keywords = ["hello", "hi", "how are you", "goodbye", "great"]completer = MyCompleter(keywords)readline.set_completer(completer.complete)readline.parse_and_bind('tab: complete')for kw in keywords:    readline.add_history(kw)input = raw_input("Input: ")print "You entered", input

运行脚本时,请尝试输入

Ctrl
+,
r
然后输入
a
。这将返回包含“
a”的第一个匹配项。再次输入
Ctrl
+
r
以进行下一场比赛。要选择一个条目,请按
ENTER

也可以尝试使用UP / DOWN键在关键字中滚动。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/636815.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号