2011-07-27 21 views
2

有沒有一個通用圖書館,可以讓我有自動完成根據自定義語法和項目列表?是否有自定義自動完成的Python庫?

下面是我正在尋找的一個例子。

語法:

  • 可以咀嚼蘋果和芒果
  • 可以喝牛奶和水
  • 您可以將一切
  • 句子結構:動詞[+形容詞] +對象

項目:

  • 1個青蘋果
  • 1微觀蘋果
  • 1綠色芒果
  • 1黃色芒果
  • 1芒果[無給定顏色]
  • 1牛奶
  • 1水

預期行爲(用戶在第一行輸入,第二行建議)

m 
move, munch 

mo 
move 

move g 
move green apple, move green mango 

move y 
move yellow mango 

move m 
move milk, move mango, move microscopic apple 
+0

可能重複[如何使一個Python,命令行程序自動完成任意東西不解釋(http://stackoverflow.com/questions/187621/how-to-make-a-python-command-line-program-autocomplete-any-things-not-inte) –

+1

@ S.Lott - 你被標記爲「完全重複」的問題 - 相關 - **它是不是重複的**。該問題只涉及基於其他字符串列表完成字符串。我的問題是關於定義語法規則,然後基於此做自動完成。 :) – mac

+0

請**更新**您的問題,以明確您的問題與其他似乎完全相同的問題。您可能想要搜索** all **其他Python自動完成問題,並確定與之前所有問題的具體區別。 –

回答

2

我終於找到了一個可接受的解決方案,通過使用SPARK(用於語法分析/語法分析)和我自己的代碼進行自動完成。

關於SPARK

SPARK代表了掃描,分析和重寫套件。它以前的 沒有名字,被稱爲「小語言框架」。 在第七屆國際Python會議論文Compiling Little Languages in Python中描述了第一個版本(大約1998年)。

SPARK是用100%純Python編寫的,並且可以作爲開放的 源文件使用。

自動完成代碼

在下面的代碼:

  • category是我們自動填充的那種詞。這是通過解析當前命令行獲得的。例如:如果用戶輸入「drink m」,則解析器將知道在語法中定義的類別「流體」中有一個單詞。
  • 用戶輸入存儲在一個列表(self.chars
  • _get_list_of_existing()在給定的類別返回現有單詞的列表
  • _get_common_beginning()回報 - 如果有的話 - 用於多個匹配的最長的初始超層。例如,如果用戶輸入的是「ma」並且可能的自動完成字是[magnolia,magnifying glass]_get_common_beginning()將返回「magn」

下面是相關的代碼片段:

def autocomplete(self, category): 
    ''' 
    If possible, autocomplete a word according to its category. 
    ''' 
    root = ''.join(self.chars).split()[-1] #The bit after the last space 
    pool = self._get_list_of_existing(category) 
    matches = [i for i in pool if i.find(root) == 0] 
    if len(matches) == 1: 
     match = matches[0]+' ' 
    elif len(matches) > 1: 
     match = self._get_common_beginning(matches) 
    else: 
     return 
    self.chars.extend(list(match[len(root):])) 

def _get_common_beginning(self, strings): 
    ''' 
    Return the strings that is common to the beginning of each string in 
    the strings list. 
    ''' 
    result = [] 
    limit = min([len(s) for s in strings]) 
    for i in range(limit): 
     chs = set([s[i] for s in strings]) 
     if len(chs) == 1: 
      result.append(chs.pop()) 
     else: 
      break 
    return ''.join(result) 
2

一個用於自動完成的模塊我知道的是Qt的QCompleter,您可以通過PyQt或PySide在Python中使用它。我不認爲它以你的意思理解語法,但它足夠通用,可以讓你編寫代碼。