是否有用于自定义自动完成的Python库?
是否有允许我根据自定义语法和项目列表自动完成的通用库? 这是我正在寻找的一个例子 语法:是否有用于自定义自动完成的Python库?,python,parsing,user-interface,autocomplete,grammar,Python,Parsing,User Interface,Autocomplete,Grammar,是否有允许我根据自定义语法和项目列表自动完成的通用库? 这是我正在寻找的一个例子 语法: 你可以吃苹果和芒果 你可以喝牛奶和水 你可以移动任何东西 句子结构:动词[+形容词]+宾语 项目: 1个青苹果 1个显微镜下的苹果 1个绿芒果 1个黄芒果 1个芒果[没有给出颜色] 一杯牛奶 1水 预期行为(第一行为用户输入,第二行为建议) 我知道自动完成的一个模块是Qt的QCompleter,您可以通过PyQt或PySide在Python中使用它。我认为它不像你所说的那样理解语法,但它的通用性足以
- 你可以吃苹果和芒果
- 你可以喝牛奶和水
- 你可以移动任何东西
- 句子结构:动词[+形容词]+宾语
- 1个青苹果
- 1个显微镜下的苹果
- 1个绿芒果
- 1个黄芒果
- 1个芒果[没有给出颜色]
- 一杯牛奶
- 1水
我知道自动完成的一个模块是Qt的
QCompleter
,您可以通过PyQt或PySide在Python中使用它。我认为它不像你所说的那样理解语法,但它的通用性足以让你编写这样的代码。我最终找到了一个可接受的解决方案,将(用于语法分析/语法分析)和我自己的自动补全代码相结合
关于SPARK
SPARK代表扫描、解析和重写工具包。它以前
没有名字,被称为“小语言框架”
第一个版本(大约1998年)在第七届国际Python会议的论文中进行了描述
SPARK是用100%纯Python编写的,并且是开放的
来源
自动完成代码
在以下代码中:
是我们正在自动完成的词。这是通过解析当前命令行获得的。例如:如果用户正在键入“drink m”,解析器将知道应该使用语法中定义的“liquids”类别中的单词category
- 用户输入存储在列表中(
)self.chars
返回给定类别中现有单词的列表\u get\u list\u of\u existing()
返回-如果可用-多个匹配的最长初始超序列。例如,如果用户输入写“ma”,可能的自动补全词是[magnolia,放大镜],\u get\u common\u start()
将返回“magn”\u get\u common\u start()
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)
@S.Lott的可能重复-您标记为“完全重复”的问题-虽然相关-但不是重复。这个问题只涉及根据其他字符串列表完成字符串。我的问题是定义语法规则,然后在此基础上进行自动补全。:)请更新您的问题,使您的问题明显不同于其他看起来相同的问题。您可能希望搜索所有其他Python自动完成程序问题,并确定与前面所有问题的具体区别。
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)