我正在尝试为一些文本数据创建一个简单的解析器。(文本使用的语言是NLTK没有任何解析器。)
基本上,我的前缀数量有限,可以是一个或两个字母。一个单词可以有多个前缀。我的后缀数量也有限,只有一两个字母。它们之间的任何内容都应该是单词的“根”。许多单词将具有一个可能解析的更多内容,因此我想输入一个单词并以元组(前缀,根,后缀)的形式返回可能解析的列表。
我不知道如何构造代码。我粘贴了一个示例尝试的示例(使用一些虚拟的英语数据使其更易于理解),但这显然是不正确的。一方面,它确实很丑陋且多余,所以我敢肯定,有更好的方法可以做到这一点。另一方面,它不适用于具有多个前缀或后缀,或同时具有前缀和后缀的单词。
有什么想法吗?
prefixes = ['de','con']
suffixes = ['er','s']
def parser(word):
poss_parses = []
if word[0:2] in prefixes:
poss_parses.append((word[0:2],word[2:],''))
if word[0:3] in prefixes:
poss_parses.append((word[0:3],word[3:],''))
if word[-2:-1] in prefixes:
poss_parses.append(('',word[:-2],word[-2:-1]))
if word[-3:-1] in prefixes:
poss_parses.append(('',word[:-3],word[-3:-1]))
if word[0:2] in prefixes and word[-2:-1] in suffixes and len(word[2:-2])>2:
poss_parses.append((word[0:2],word[2:-2],word[-2:-1]))
if word[0:2] in prefixes and word[-3:-1] in suffixes and len(word[2:-3])>2:
poss_parses.append((word[0:2],word[2:-2],word[-3:-1]))
if word[0:3] in prefixes and word[-2:-1] in suffixes and len(word[3:-2])>2:
poss_parses.append((word[0:2],word[2:-2],word[-2:-1]))
if word[0:3] in prefixes and word[-3:-1] in suffixes and len(word[3:-3])>2:
poss_parses.append((word[0:3],word[3:-2],word[-3:-1]))
return …Run Code Online (Sandbox Code Playgroud)