[英]How to code autocompletion in 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 )中,只有一個可能的匹配項,並且整個句子“你好”是自動完成的。
查看鏈接的文章,了解有關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 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 。
還可以嘗試使用向上/向下鍵滾動關鍵字。
要在 Python shell 中啟用自動完成功能,請鍵入:
import rlcompleter, readline
readline.parse_and_bind('tab:complete')
我猜你需要讓用戶按下一個鍵。
您可以使用以下方法實現它(無需按 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
然后,如果此鍵是 Tab 鍵(例如,這是您需要實現的),則向用戶顯示所有可能性。 如果這是任何其他鍵,請將其打印在標准輸出上。
哦,當然你需要讓 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
我現在遇到的問題是顯示標志的方式,您剛剛輸入時沒有任何輸入和空格, print a
和print a,
作用。
您可能想簽出快速自動完成: 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']]
免責聲明:我寫了快速自動完成。
腳步:
通過以下命令在主目錄中創建一個文件 .pythonrc: vi .pythonrc
輸入此內容:
import rlcompleter, readline readline.parse_and_bind('tab:complete')
關閉文件
現在運行
echo "export PYTHONSTARTUP=~/.pythonrc" >> ~/.bashrc
重啟終端
對於那些最終在解釋器中搜索自動完成的人(像我一樣):
這涉及創建文件.pythonrc
、修改.bashrc
和每次啟動 Python 解釋器時都必須導入的import sys
。
我想知道后者是否可以自動化以獲得更多勝利。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.