Is it possible to get a set of a specific named entity tokens that comprise a phrase

纵饮孤独 提交于 2019-12-07 23:44:29

After discussions on the mailing list I've found that the api does not support this. My solution was to just keep the state of the last NE, and build a string if necessary. John B. from the nlp mailing lists was helpful in answering my question.

The named entity tagger and part-of-speech tagger are distinct algorithms within the CoreNLP pipeline and it seems the API consumer is tasked with integrating them.

Please forgive my C# but here is a simple class:

    public class NamedNounPhrase
    {
        public NamedNounPhrase()
        {
            Phrase = string.Empty;
            Tags = new List<string>();
        }

        public string Phrase { get; set; }

        public IList<string> Tags { get; set; }

    }

and some code to find all the top-level noun phrases and their associated named entity tags:

    private void _monkey()
    {

        ...

        var nounPhrases = new List<NamedNounPhrase>();

        foreach (CoreMap sentence in sentences.toArray())
        {
            var tree =
                (Tree)sentence.get(new TreeCoreAnnotations.TreeAnnotation().getClass());

            if (null != tree)
                _walk(tree, nounPhrases);
        }

        foreach (var nounPhrase in nounPhrases)
            Console.WriteLine(
                "{0} ({1})",
                nounPhrase.Phrase,
                string.Join(", ", nounPhrase.Tags)
                );
    }

    private void _walk(Tree tree, IList<NamedNounPhrase> nounPhrases)
    {
        if ("NP" == tree.value())
        {
            var nounPhrase = new NamedNounPhrase();

            foreach (Tree leaf in tree.getLeaves().toArray())
            {
                var label = (CoreLabel) leaf.label();
                nounPhrase.Phrase += (string) label.get(new CoreAnnotations.TextAnnotation().getClass()) + " ";
                nounPhrase.Tags.Add((string) label.get(new CoreAnnotations.NamedEntityTagAnnotation().getClass()));
            }

            nounPhrases.Add(nounPhrase);
        }
        else
        {
            foreach (var child in tree.children())
            {
                _walk(child, nounPhrases);
            }
        }
    }

Hope that helps!

MFARID

Thanks a lot, I was going to do the same. The Stanford NER API, however, supports classifyToCharOffset (or something like that) to get the whole phrase. I don't know, maybe it is just an implementation of your idea :D.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!