从树结构生成规则,有re但不能没有nltk



我想在不使用自然语言工具包(NLTK)的情况下从树结构中提取规则
对于ex;树结构为:

( NP-TMP ( NNP December  )  ( CD 1998  )  )  n

我想提取这样的规则:

NP-TMP -> NNP CD
NNP -> 'December'
CD -> '1998'

在不使用"nltk"的情况下,如何使用Python中的re库实现这一点?

是一个非常不优雅的解决方案

import re
s_expr = "( NP-TMP ( NNP December  )  ( CD 1998  )  )"
regex = re.compile("([\w-]+)")
matches = re.findall(regex, s_expr)
# assert the s-expressions are 5
assert (len(matches) == 5)
print matches[0], matches[1], matches[3]
print matches[1], matches[2]
print matches[3], matches[4]

在这里,我假设所有的s表达式或树都有两个子代,如果没有,这将不起作用,也许手工语法分析器比正则表达式更好。

相关内容

最新更新