python - NLTK CFG 多个单词语法

标签 python parsing nlp nltk python-3.4

NLTK 3.0:

使用如下所示的 CFG 配置(非终结符团队有 4 个值,其中 1 个值有 2 个单词(斯里兰卡)。

当我生成可能的世代列表时,我可以看到结果中出现两个单词。但是当我尝试用这两个单词语法解析输入句子时,它不会解析。

import nltk
from nltk.parse import generate
from nltk.grammar import Nonterminal


cfg = nltk.CFG.fromstring("""
root -> who_player has the most runs
who_player -> who
who_player -> which player
who_player -> which team player
who -> 'who'
which -> 'which'
player -> 'player'
team -> 'indian' | 'australian' | 'england' | 'sri lankan'
has -> 'has'
the -> 'the'
this -> 'this'
most -> 'most'
runs -> 'runs'
""")

print(list((n,sent) for n, sent in enumerate(generate.generate(cfg, n=100, start=Nonterminal('root')), 1)))

# Above generate generates ['which', 'sri lankan', 'player', 'has', 'the', 'most', 'runs']
# But the same sentence is not parsable by ChartParser.

result1 = nltk.ChartParser(cfg).parse('which england player has the most runs'.split())
print(list(result1))
result2 = nltk.ChartParser(cfg).parse('which sri lankan player has the most runs'.split()) # Does not work.
print(list(result2))

如何使用 ChartParser 进行多字配置。

最佳答案

管道将图表中的节点分隔开,空格将单个单词与多单词表达式分隔开。多字表达式将创建一棵树,其中列表中包含两个项目。

team -> 'indian' | 'australian' | 'england' | 'sri' 'lankan'

[输出]:

[Tree('root', [Tree('who_player', [Tree('which', ['which']), Tree('team', ['sri', 'lankan']), Tree('player', ['player'])]), Tree('has', ['has']), Tree('the', ['the']), Tree('most', ['most']), Tree('runs', ['runs'])])]

关于python - NLTK CFG 多个单词语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29302518/

相关文章:

python - 有没有办法在Python中获取元组或列表的差异和交集?

python - 我的解决方案有什么问题?最大计数[Codechef]

PHP Xpath 为属性名称为 ="author"的节点提取值

python - 识别文本中的多个类别和相关情绪

python - 使用 scipy 的低阶近似

python - Pycharm 剧照在重命名 .py 文件后显示旧名称。如何解决这个问题?

python - DecisiontreeClassifier,为什么值的总和错误?

c# - 从 JSON 反序列化大量属性

html - 使用 perl 去除 HTML 标签

python - 具有适用于 Word2Vec 模型的 Keras 功能 API 的产品合并层