SPARK stands for the Scanning, Parsing, and Rewriting Kit. It formerly
had no name, and was referred to as the "little language framework."
The first version (circa 1998) was described in the paper Compiling
Little Languages in Python at the 7th International Python Conference.
SPARK is written in 100% pure Python, and is made available as open
source.
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)
我最终找到了一个可接受的解决方案,它使用了SPARK(用于语法分析/语法分析)和我自己的自动完成代码。在
关于SPARK
自动完成代码
在以下代码中:
category
是我们正在自动完成的单词。这是通过解析当前命令行获得的。例如:如果用户输入的是“drink m”,解析器将知道语法中定义的类别为“liquids”的单词。在self.chars
)_get_list_of_existing()
返回给定类别中现有单词的列表_get_common_beginning()
返回-如果可用-多个匹配项的最长初始超序列。例如,如果用户输入正在写入“ma”,并且可能的自动补全单词是[magnolia,magnaling glass],则_get_common_beginning()
将返回“magn”。在以下是相关代码片段:
我知道的一个自动完成模块是Qt的
QCompleter
,可以通过PyQt或PySide在Python中使用它。我不认为它能像你所说的那样理解语法,但它的通用性足以让你编写这样的代码。在相关问题 更多 >
编程相关推荐