如何编写代码来自动完成单词和句子? [英] How to write code to autocomplete words and sentences?

查看:29
本文介绍了如何编写代码来自动完成单词和句子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to write code that does autocompletion in the Linux terminal. The code should work as follows.

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

It has a list of strings (e.g. "hello, "hi", "how are you", "goodbye", "great", ...).

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

In the terminal, the user will start typing and when there is some match possibility, he gets the hint for possible strings, from which he can choose (similarly as in vim editor or google incremental search).

例如他开始输入h",然后他得到提示

e.g. he starts typing "h", and he gets the hint

你好"

_我"

_你好吗"

如果它不仅可以从开头完成单词,还可以从字符串的任意部分完成单词,那就更好了.

And better yet would be if it would complete words not only from the beginning, but from an arbitrary part of the string.

推荐答案

(我知道这不是您要的,但是)如果您对出现的自动完成/建议感到满意TAB(在许多 shell 中使用),然后您可以使用 readline 模块.

(I'm aware this isn't exactly what you're asking for, but) If you're happy with the auto-completion/suggestions appearing on TAB (as used in many shells), then you can quickly get up and running using the readline module.

这是一个基于 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 键):

This results in the following behaviour (<TAB> representing a the tab key being pressed):

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

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

In the last line (HOTAB entered), there is only one possible match and the whole sentence "how are you" is auto completed.

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

Check out the linked articles for more information on readline.

如果它不仅从头开始完成单词……从字符串的任意部分完成,那就更好了."

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

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

This can be achieved by simply modifying the match criteria in the completer function, ie. from:

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

<小时>

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

创建用于滚动/搜索的伪菜单的一种简单方法是将关键字加载到历史缓冲区中.然后,您将能够使用向上/向下箭头键滚动条目以及使用 Ctrl+R 执行反向搜索.

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

To try this out, make the following changes:

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.

When you run the script, try typing Ctrl+r followed by a. That will return the first match that contains "a". Enter Ctrl+r again for the next match. To select an entry, press ENTER.

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

Also try using the UP/DOWN keys to scroll through the keywords.

这篇关于如何编写代码来自动完成单词和句子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆