- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我已经从 atis 语法生成了语法,现在我想添加一些我自己的规则,特别是来自句子的终端,我可以这样做吗?
import nltk
grammar = nltk.data.load('grammars/large_grammars/atis.cfg')
到语法
我想添加更多的终端。
最佳答案
简而言之:是的,这是可能的,但你会经历很多痛苦,使用 atis.cfg
作为基础重写你的 CFG 更容易,然后阅读新的 CFG 文本文件。这比将每个新终端重新分配给正确的非终端来映射它们更容易
中长,看下面
首先让我们看看NLTK中的CFG文法是什么,它包含什么:
>>> import nltk
>>> g = nltk.data.load('grammars/large_grammars/atis.cfg')
>>> dir(g)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__unicode__', '__weakref__', '_all_unary_are_lexical', '_calculate_grammar_forms', '_calculate_indexes', '_calculate_leftcorners', '_categories', '_empty_index', '_immediate_leftcorner_categories', '_immediate_leftcorner_words', '_is_lexical', '_is_nonlexical', '_leftcorner_parents', '_leftcorner_words', '_leftcorners', '_lexical_index', '_lhs_index', '_max_len', '_min_len', '_productions', '_rhs_index', '_start', 'check_coverage', 'fromstring', 'is_binarised', 'is_chomsky_normal_form', 'is_flexible_chomsky_normal_form', 'is_leftcorner', 'is_lexical', 'is_nonempty', 'is_nonlexical', 'leftcorner_parents', 'leftcorners', 'max_len', 'min_len', 'productions', 'start', 'unicode_repr']
有关详细信息,请参阅 https://github.com/nltk/nltk/blob/develop/nltk/grammar.py#L421
终端和非终端似乎都是Production
类型,参见https://github.com/nltk/nltk/blob/develop/nltk/grammar.py#L236 ,即
A grammar production. Each production maps a single symbol on the "left-hand side" to a sequence of symbols on the "right-hand side". (In the case of context-free productions, the left-hand side must be a
Nonterminal
, and the right-hand side is a sequence of terminals andNonterminals
.) "terminals" can be any immutable hashable object that is not aNonterminal
. Typically, terminals are strings representing words, such as"dog"
or"under"
.
那么让我们来看看语法是如何存储产生式的:
>>> type(g._productions)
<type 'list'>
>>> g._productions[-1]
zero -> 'zero'
>>> type(g._productions[-1])
<class 'nltk.grammar.Production'>
现在,似乎我们可以创建 nltk.grammar.Production
对象并将它们附加到 grammar._productions
。
让我们尝试使用原始语法:
>>> import nltk
>>> original_grammar = nltk.data.load('grammars/large_grammars/atis.cfg')
>>> original_parser = ChartParser(original_grammar)
>>> sent = ['show', 'me', 'northwest', 'flights', 'to', 'detroit', '.']
>>> for i in original_parser.parse(sent):
... print i
... break
...
(SIGMA
(IMPR_VB
(VERB_VB (show show))
(NP_PPO
(pt_pron_ppo me)
(NAPPOS_NP (NOUN_NP (northwest northwest))))
(NP_NNS (NOUN_NNS (pt207 flights)) (PREP_IN (to to)))
(AVPNP_NP (NOUN_NP (detroit detroit)))
(pt_char_per .)))
原始语法没有终结符singapore
:
>>> sent = ['show', 'me', 'northwest', 'flights', 'to', 'singapore', '.']
>>> for i in original_parser.parse(sent):
... print i
... break
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/nltk/parse/api.py", line 49, in parse
return iter(self.parse_all(sent))
File "/usr/local/lib/python2.7/dist-packages/nltk/parse/chart.py", line 1350, in parse_all
chart = self.chart_parse(tokens)
File "/usr/local/lib/python2.7/dist-packages/nltk/parse/chart.py", line 1309, in chart_parse
self._grammar.check_coverage(tokens)
File "/usr/local/lib/python2.7/dist-packages/nltk/grammar.py", line 631, in check_coverage
"input words: %r." % missing)
ValueError: Grammar does not cover some of the input words: u"'singapore'".
在我们尝试将singapore
添加到语法中之前,让我们看看detroit
是如何存储在语法中的:
>>> original_grammar._rhs_index['detroit']
[detroit -> 'detroit']
>>> type(original_grammar._rhs_index['detroit'])
<type 'list'>
>>> type(original_grammar._rhs_index['detroit'][0])
<class 'nltk.grammar.Production'>
>>> original_grammar._rhs_index['detroit'][0]._lhs
detroit
>>> original_grammar._rhs_index['detroit'][0]._rhs
(u'detroit',)
>>> type(original_grammar._rhs_index['detroit'][0]._lhs)
<class 'nltk.grammar.Nonterminal'>
>>> type(original_grammar._rhs_index['detroit'][0]._rhs)
<type 'tuple'>
>>> original_grammar._rhs_index[original_grammar._rhs_index['detroit'][0]._lhs]
[NOUN_NP -> detroit, NOUN_NP -> detroit minneapolis toronto]
现在我们可以尝试为 singapore
重新创建相同的 Production
对象:
# First let's create Non-terminal for singapore.
>>> nltk.grammar.Nonterminal('singapore')
singapore
>>> lhs = nltk.grammar.Nonterminal('singapore')
>>> rhs = [u'singapore']
# Now we can create the Production for singapore.
>>> singapore_production = nltk.grammar.Production(lhs, rhs)
# Now let's try to add this Production the grammar's list of production
>>> new_grammar = nltk.data.load('grammars/large_grammars/atis.cfg')
>>> new_grammar._productions.append(singapore_production)
但它仍然无法正常工作,但因为提供终端本身并不能真正帮助将其与 CFG 的其余部分相关联,因此新加坡仍然无法解析:
>>> new_grammar = nltk.data.load('grammars/large_grammars/atis.cfg')
>>> new_grammar._productions.append(singapore_production)
>>> new_parser = ChartParser(new_grammar)
>>> sent = ['show', 'me', 'northwest', 'flights', 'to', 'singapore', '.']
>>> new_parser.parse(sent)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/nltk/parse/api.py", line 49, in parse
return iter(self.parse_all(sent))
File "/usr/local/lib/python2.7/dist-packages/nltk/parse/chart.py", line 1350, in parse_all
chart = self.chart_parse(tokens)
File "/usr/local/lib/python2.7/dist-packages/nltk/parse/chart.py", line 1309, in chart_parse
self._grammar.check_coverage(tokens)
File "/usr/local/lib/python2.7/dist-packages/nltk/grammar.py", line 631, in check_coverage
"input words: %r." % missing)
ValueError: Grammar does not cover some of the input words: u"'singapore'".
从下面我们知道新加坡就像底特律,底特律通向这个Left-handside LHS NOUN_NP -> detroit
:
>>> original_grammar._rhs_index[original_grammar._rhs_index['detroit'][0]._lhs]
[NOUN_NP -> detroit, NOUN_NP -> detroit minneapolis toronto]
因此,我们需要做的是为新加坡添加另一个导致 NOUN_NP
非终结符的产生式,或者将我们的新加坡 LHS 附加到 NOUN_NP 非终结符的右侧:
>>> lhs = nltk.grammar.Nonterminal('singapore')
>>> rhs = [u'singapore']
>>> singapore_production = nltk.grammar.Production(lhs, rhs)
>>> new_grammar._productions.append(singapore_production)
现在让我们为 NOUN_NP -> singapore
添加新产生式:
lhs2 = nltk.grammar.Nonterminal('NOUN_NP')
new_grammar._productions.append(nltk.grammar.Production(lhs2, [lhs]))
现在我们应该期望我们的解析器可以工作了:
sent = ['show', 'me', 'northwest', 'flights', 'to', 'singapore', '.']
print new_grammar.productions()[2091]
print new_grammar.productions()[-1]
new_parser = nltk.ChartParser(new_grammar)
for i in new_parser.parse(sent):
print i
[输出]:
Traceback (most recent call last):
File "test.py", line 31, in <module>
for i in new_parser.parse(sent):
File "/usr/local/lib/python2.7/dist-packages/nltk/parse/api.py", line 49, in parse
return iter(self.parse_all(sent))
File "/usr/local/lib/python2.7/dist-packages/nltk/parse/chart.py", line 1350, in parse_all
chart = self.chart_parse(tokens)
File "/usr/local/lib/python2.7/dist-packages/nltk/parse/chart.py", line 1309, in chart_parse
self._grammar.check_coverage(tokens)
File "/usr/local/lib/python2.7/dist-packages/nltk/grammar.py", line 631, in check_coverage
"input words: %r." % missing)
ValueError: Grammar does not cover some of the input words: u"'singapore'".
但看起来语法仍然无法识别我们添加的新终结符和非终结符,所以让我们尝试破解并将我们的新语法输出到字符串中,并从输出字符串创建一个更新的语法:
import nltk
lhs = nltk.grammar.Nonterminal('singapore')
rhs = [u'singapore']
singapore_production = nltk.grammar.Production(lhs, rhs)
new_grammar = nltk.data.load('grammars/large_grammars/atis.cfg')
new_grammar._productions.append(singapore_production)
lhs2 = nltk.grammar.Nonterminal('NOUN_NP')
new_grammar._productions.append(nltk.grammar.Production(lhs2, [lhs]))
# Create newer grammar from new_grammar's string
newer_grammar = nltk.grammar.CFG.fromstring(str(new_grammar).split('\n')[1:])
# Reassign new_grammar's string to newer_grammar !!!
newer_grammar._start = new_grammar.start()
newer_grammar
sent = ['show', 'me', 'northwest', 'flights', 'to', 'singapore', '.']
print newer_grammar.productions()[2091]
print newer_grammar.productions()[-1]
newer_parser = nltk.ChartParser(newer_grammar)
for i in newer_parser.parse(sent):
print i
break
[输出]:
(SIGMA
(IMPR_VB
(VERB_VB (show show))
(NP_PPO
(pt_pron_ppo me)
(NAPPOS_NP (NOUN_NP (northwest northwest))))
(NP_NNS (NOUN_NNS (pt207 flights)) (PREP_IN (to to)))
(AVPNP_NP (NOUN_NP (singapore singapore)))
(pt_char_per .)))
关于python - NLTK:我可以将终端添加到已经生成的语法中吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27869416/
我需要将文本放在 中在一个 Div 中,在另一个 Div 中,在另一个 Div 中。所以这是它的样子: #document Change PIN
奇怪的事情发生了。 我有一个基本的 html 代码。 html,头部, body 。(因为我收到了一些反对票,这里是完整的代码) 这是我的CSS: html { backgroun
我正在尝试将 Assets 中的一组图像加载到 UICollectionview 中存在的 ImageView 中,但每当我运行应用程序时它都会显示错误。而且也没有显示图像。 我在ViewDidLoa
我需要根据带参数的 perl 脚本的输出更改一些环境变量。在 tcsh 中,我可以使用别名命令来评估 perl 脚本的输出。 tcsh: alias setsdk 'eval `/localhome/
我使用 Windows 身份验证创建了一个新的 Blazor(服务器端)应用程序,并使用 IIS Express 运行它。它将显示一条消息“Hello Domain\User!”来自右上方的以下 Ra
这是我的方法 void login(Event event);我想知道 Kotlin 中应该如何 最佳答案 在 Kotlin 中通配符运算符是 * 。它指示编译器它是未知的,但一旦知道,就不会有其他类
看下面的代码 for story in book if story.title.length < 140 - var story
我正在尝试用 C 语言学习字符串处理。我写了一个程序,它存储了一些音乐轨道,并帮助用户检查他/她想到的歌曲是否存在于存储的轨道中。这是通过要求用户输入一串字符来完成的。然后程序使用 strstr()
我正在学习 sscanf 并遇到如下格式字符串: sscanf("%[^:]:%[^*=]%*[*=]%n",a,b,&c); 我理解 %[^:] 部分意味着扫描直到遇到 ':' 并将其分配给 a。:
def char_check(x,y): if (str(x) in y or x.find(y) > -1) or (str(y) in x or y.find(x) > -1):
我有一种情况,我想将文本文件中的现有行包含到一个新 block 中。 line 1 line 2 line in block line 3 line 4 应该变成 line 1 line 2 line
我有一个新项目,我正在尝试设置 Django 调试工具栏。首先,我尝试了快速设置,它只涉及将 'debug_toolbar' 添加到我的已安装应用程序列表中。有了这个,当我转到我的根 URL 时,调试
在 Matlab 中,如果我有一个函数 f,例如签名是 f(a,b,c),我可以创建一个只有一个变量 b 的函数,它将使用固定的 a=a1 和 c=c1 调用 f: g = @(b) f(a1, b,
我不明白为什么 ForEach 中的元素之间有多余的垂直间距在 VStack 里面在 ScrollView 里面使用 GeometryReader 时渲染自定义水平分隔线。 Scrol
我想知道,是否有关于何时使用 session 和 cookie 的指南或最佳实践? 什么应该和什么不应该存储在其中?谢谢! 最佳答案 这些文档很好地了解了 session cookie 的安全问题以及
我在 scipy/numpy 中有一个 Nx3 矩阵,我想用它制作一个 3 维条形图,其中 X 轴和 Y 轴由矩阵的第一列和第二列的值、高度确定每个条形的 是矩阵中的第三列,条形的数量由 N 确定。
假设我用两种不同的方式初始化信号量 sem_init(&randomsem,0,1) sem_init(&randomsem,0,0) 现在, sem_wait(&randomsem) 在这两种情况下
我怀疑该值如何存储在“WORD”中,因为 PStr 包含实际输出。? 既然Pstr中存储的是小写到大写的字母,那么在printf中如何将其给出为“WORD”。有人可以吗?解释一下? #include
我有一个 3x3 数组: var my_array = [[0,1,2], [3,4,5], [6,7,8]]; 并想获得它的第一个 2
我意识到您可以使用如下方式轻松检查焦点: var hasFocus = true; $(window).blur(function(){ hasFocus = false; }); $(win
我是一名优秀的程序员,十分优秀!