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

xra*_*alf 32 python autocomplete type-hinting

我想在Linux终端中编写自动完成代码.代码应该如下工作.

它有一个字符串列表(例如"hello","hi","你好吗","再见","很棒",......).

在终端中,用户将开始键入,并且当存在一些匹配可能性时,他获得可能的字符串的提示,他可以从中选择(类似于vim编辑器谷歌增量搜索).

例如,他开始输入"h"并获得提示

你好"

_ "一世"

_"你是不是"

更好的是,如果它不仅从头开始,而且从字符串的任意部分完成单词.

谢谢你的建议.

Sha*_*hin 45

(我知道这不是你要求的,但是)如果你对出现的自动完成/建议感到满意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
Run Code Online (Sandbox Code Playgroud)

这会导致以下行为(<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
Run Code Online (Sandbox Code Playgroud)

在最后一行(HOTAB输入)中,只有一个可能的匹配,并且整个句子"你好吗"是自动完成的.

查看链接的文章以获取更多信息readline.


"而且更好的是,如果它不仅从一开始就完成单词......从字符串的任意部分完成."

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

self.matches = [s for s in self.options 
                   if s and s.startswith(text)]
Run Code Online (Sandbox Code Playgroud)

类似于:

self.matches = [s for s in self.options 
                   if text in s]
Run Code Online (Sandbox Code Playgroud)

这将给您以下行为:

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

Input: o<TAB><TAB>
goodbye      hello        how are you
Run Code Online (Sandbox Code Playgroud)

更新:使用历史缓冲区(如评论中所述)

创建用于滚动/搜索的伪菜单的简单方法是将关键字加载到历史缓冲区中.然后,您可以使用向上/向下箭头键滚动条目,也可以使用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
Run Code Online (Sandbox Code Playgroud)

运行脚本时,请尝试键入Ctrl+ r后跟a.这将返回包含"a"的第一个匹配.再次输入Ctrl+ r以进行下一场比赛.要选择条目,请按ENTER.

还可以尝试使用向上/向下键滚动关键字.


小智 8

要在 Python shell 中启用自动完成功能,请键入:

import rlcompleter, readline
readline.parse_and_bind('tab:complete')
Run Code Online (Sandbox Code Playgroud)

(感谢http://blog.e-shell.org/221


Gan*_*ndi 6

我想你需要得到一个用户按下的键.

您可以使用以下方法实现它(无需按Enter键):

import termios, os, sys

def getkey():
    fd = sys.stdin.fileno()
    old = termios.tcgetattr(fd)
    new = termios.tcgetattr(fd)
    new[3] = new[3] & ~termios.ICANON & ~termios.ECHO
    new[6][termios.VMIN] = 1
    new[6][termios.VTIME] = 0
    termios.tcsetattr(fd, termios.TCSANOW, new)
    c = None
    try:
        c = os.read(fd, 1)
    finally:
        termios.tcsetattr(fd, termios.TCSAFLUSH, old)
    return c
Run Code Online (Sandbox Code Playgroud)

然后,如果此键是Tab键(例如,您需要实现的那些键),则向用户显示所有可能性.如果是其他任何键,请在stdout上打印.

哦,当然,只要用户点击进入,你就需要在一段时间内使用getkey()循环.你也可以得到一个像raw_input这样的方法,当你点击一个标签时,它会逐个符号地显示整个单词,或者显示所有可能性.

至少那是项目,你可以先开始.如果你遇到任何其他问题,那就写下来吧.

编辑1:

get_word方法可能如下所示:

def get_word():
    s = ""
    while True:
        a = getkey()
        if a == "\n":
            break
        elif a == "\t":
            print "all possibilities"
        else:
            s += a

    return s

word = get_word()
print word
Run Code Online (Sandbox Code Playgroud)

我存在的,现在的问题是要显示一个标志的方式,你刚才输入没有任何enteres和空格,都什么print aprint a,做.


Sep*_*man 5

您可能想签出快速自动完成:https : //github.com/seperman/fast-autocomplete

它有一个演示模式,您可以在输入时输入并获取结果:https : //zepworks.com/posts/you-autocomplete-me/#part-6-demo

这是非常容易使用:

>>> from fast_autocomplete import AutoComplete
>>> words = {'book': {}, 'burrito': {}, 'pizza': {}, 'pasta':{}}
>>> autocomplete = AutoComplete(words=words)
>>> autocomplete.search(word='b', max_cost=3, size=3)
[['book'], ['burrito']]
>>> autocomplete.search(word='bu', max_cost=3, size=3)
[['burrito']]
>>> autocomplete.search(word='barrito', max_cost=3, size=3)  # mis-spelling
[['burrito']]
Run Code Online (Sandbox Code Playgroud)

免责声明:我写了快速自动完成。