gpt4 book ai didi

python - NLTK CFG 多个单词语法

转载 作者:行者123 更新时间:2023-12-01 04:46:21 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com