自动编写python,如何在python中编写自动完成?

(我知道这并不完全符合您的要求,但是如果您对TAB中出现的自动完成/建议感到满意(如许多shell中所使用的),则可以快速启动并运行使用

readline模块。

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:

goodbye great hello hi how are you

Input: h

hello hi how are you

Input: hoow are you

在最后一行(HOTAB输入)中,只有一个可能的匹配,整个句子“你好”是自动完成的。

查看链接的文章,了解更多关于readline的信息。

“And better yet would be if it would complete words not only from the beginning … completion from arbitrary part of the string.”

这可以通过简单地修改完成函数中的匹配标准来实现,即。从:

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:

goodbye great hello hi how are you

Input: o

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键滚动浏览关键字。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值