如何解决如何在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
输入的)中,只有一个可能的匹配项,并且整个句子“你好吗”是自动完成的。
“更好的情况是,它不仅可以从头开始完成单词,而且可以从字符串的任意部分完成单词。”
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
进行反向搜索。
要尝试此操作,请进行以下更改:
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键在关键字中滚动。
解决方法
我想在Linux终端中编写自动完成代码。该代码应按以下方式工作。
它具有字符串列表(例如,“ hello”,“ hi”,“你好”,“再见”,“很棒”等)。
在终端中,用户将开始输入内容,当有匹配的可能性时,他会提示可能的字符串,供他选择(类似于vim编辑器或google增量搜索)。
例如,他开始输入“ h”,他得到提示
你好”
_ “一世”
_“你好吗”
更好的是,它不仅可以从字符串的开头而且可以从字符串的任意部分完成单词。
谢谢你的指教。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。