【问题标题】:nltk extract nounphrase with RegexpParsernltk 使用 RegexpParser 提取名词短语
【发布时间】:2020-03-24 13:49:52
【问题描述】:

我想从文本中提取名词短语,我将 python 与 NLTK 结合使用。 我在互联网上发现了一种使用 RegexpParser 的模式,如下所示:

grammar = r"""
        NBAR:
            {<NN.*|JJ>*<NN.*>}  # Nouns and Adjectives, terminated with Nouns
        NP:
            {<NBAR>}
            {<NBAR><IN><NBAR>}  # Above, connected with in/of/etc...
    """
    cp = nltk.RegexpParser(grammar)

我想修改语法变量以添加“名词的名词”或“名词中的名词”的情况(例如“cup of coffee”或“water in cup”) 我的测试字符串是:'邮政编码是新的交付方式' 我想收到短语列表:['portal code', 'new method','new method of delivery']

【问题讨论】:

    标签: parsing nltk


    【解决方案1】:

    我的答案是:

    def ExtractNP(text):
    nounphrases = []
    words = nltk.word_tokenize(text)
    tagged = nltk.pos_tag(words)
    grammar = r"""
         NP:
            {<JJ*><NN+><IN><NN>}
            {<NN.*|JJ>*<NN.*>}
        """
    chunkParser = nltk.RegexpParser(grammar)
    tree = chunkParser.parse(tagged)
    for subtree in tree.subtrees(filter=lambda t: t.label() == 'NP'):
        myPhrase = ''
        for item in subtree.leaves():
            myPhrase += ' ' + item[0]
        nounphrases.append(myPhrase.strip())
        # print(myPhrase)
    nounphrases = list(filter(lambda x: len(x.split()) > 1, nounphrases))
    return nounphrases
    

    实际上,这并不是什么新鲜事,但我发现语法回归是按他们声明的那样有序地分块的。这意味着输入句子('邮政编码是新的投递方式')将被剪切到匹配的内容

    {<JJ*><NN+><IN><NN>}
    

    ('新的投递方式'),然后将剩下的('邮政编码是')进行比较并用于下次匹配

    {<NN.*|JJ>*<NN.*>}
    

    返回“邮政编码”。因此,我们无法在返回的结果中获得“新方法”。

    【讨论】:

      猜你喜欢
      • 2019-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-31
      • 1970-01-01
      • 2015-03-29
      • 1970-01-01
      相关资源
      最近更新 更多