【问题标题】:NLTK python variable in CFGCFG 中的 NLTK python 变量
【发布时间】:2021-04-14 15:14:44
【问题描述】:

这是我目前的 NLTK python 语法:

cfg_2 = CFG.fromstring("""
S -> ADVP VP P
S -> VP NP P
S -> VP P
ADVP -> RB
VP -> VB NP
VP -> VB PP
VP -> VB
VP -> VP CC ADVP VP
NP -> DT NML
VP -> VB NP PP
VP -> VB CC VB
NP -> NP A NP CC NP
NP -> DT NN
NP -> NN
NP -> PRP
NP -> NML NN
PP -> IN NP
NML -> NN CC NN
NML -> CD 
  DT -> 'the'|'a'
  NN -> 'carrots'|'celery'|'courgette'|'garlic'|'onion'|'leek'|'oregano'|'vegetables'|'bowl'|'ends'|'slices'|'beans'|'cannellini'|'water'|'potato'
  VB -> 'chop'|'trim'|'peel'|'add'|'cut'|'wash'|'quarter'|'scrub'|'dice'|'drain'
  CC -> 'and'
  RB -> 'roughly'|'finely'|'lengthways'|'now'|'then'
  JJ -> 'large'
  A -> ','
  P -> '.'
  IN -> 'off'|'under'|'into'|'to'
  CD -> '2'
  PRP -> 'it'
""".format(noun_string))

如您所见,我的 NN 名词列表很长。因此,我想把我所有的名词 在一个列表中,然后将该列表添加到 CFG。我试过这样的东西,但这不起作用,因为 CFG 本身是一个字符串:

noun_list = ['carrots','celery','courgette'
             ,'garlic','onion','leek','oregano',
             'vegetables','bowl','ends','slices','beans','cannellini','water','potato']

noun_string = "'|'".join(noun_list)
print(noun_string)

cfg_2 = CFG.fromstring("""
S -> ADVP VP P
S -> VP NP P
S -> VP P
ADVP -> RB
VP -> VB NP
VP -> VB PP
VP -> VB
VP -> VP CC ADVP VP
NP -> DT NML
VP -> VB NP PP
VP -> VB CC VB
NP -> NP A NP CC NP
NP -> DT NN
NP -> NN
NP -> PRP
NP -> NML NN
PP -> IN NP
NML -> NN CC NN
NML -> CD 
  DT -> 'the'|'a'
  NN -> {}
  VB -> 'chop'|'trim'|'peel'|'add'|'cut'|'wash'|'quarter'|'scrub'|'dice'|'drain'
  CC -> 'and'
  RB -> 'roughly'|'finely'|'lengthways'|'now'|'then'
  JJ -> 'large'
  A -> ','
  P -> '.'
  IN -> 'off'|'under'|'into'|'to'
  CD -> '2'
  PRP -> 'it'
""".format(noun_string))

有没有其他方法可以将名词列表添加到我的 CFG 中?

【问题讨论】:

  • 如果您仔细查看该格式调用生成的字符串,应该清楚格式模板缺少两个撇号。

标签: python nltk grammar


【解决方案1】:

<noun_list_goes_here> 之类的东西放在你的大字符串中。

然后做:

noun_string = "'|'".join(noun_list)
big_string = big_string.replace('<noun_list_goes_here>', f"'{noun_string}'")`

【讨论】:

    猜你喜欢
    • 2015-04-05
    • 1970-01-01
    • 2010-11-09
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 2015-12-25
    • 2013-06-21
    • 1970-01-01
    相关资源
    最近更新 更多