Stanford NLP自然语序处理demo,附maven dependency

本文介绍了一个利用 Stanford CoreNLP 进行名词提取的实用工具类,该工具类能够从句子中提取出名词,并将复数名词转换为单数形式。通过配置不同的注释器,Stanford CoreNLP 可以实现词性标注、命名实体识别等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

################################################    Demo     ######################################

/*

 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package framework.webapp.commons.utils;


import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.util.CoreMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 *  将句子中的名词取出,复数形式自动转为单数
 * @author mly
 */
public class NLPUtil {
    private static final Log log = LogFactory.getLog(NLPUtil.class);
    public static StanfordCoreNLP pipeline;


    static {
        // creates a StanfordCoreNLP object, with POS tagging, lemmatization, NER, parsing, and coreference resolution 
        Properties props = new Properties();
        props.setProperty("annotators", "tokenize, ssplit, pos, lemma, ner, parse, dcoref");
        pipeline = new StanfordCoreNLP(props);
    }
    
    public static StanfordCoreNLP getStanfordCoreNLP() {
        if (pipeline == null) {
            pipeline = new StanfordCoreNLP();
        }
        return pipeline;
    }


    public static List<String> getTagsForSentence(String text) {
        Annotation document = new Annotation(text);
        // run all Annotators on this text
        getStanfordCoreNLP().annotate(document);


        // these are all the sentences in this document
        // a CoreMap is essentially a Map that uses class objects as keys and has values with custom types
        List<CoreMap> sentences = document.get(CoreAnnotations.SentencesAnnotation.class);
        StringBuilder sb = new StringBuilder();
        List<String> tags = new ArrayList<String>();
        for (CoreMap sentence : sentences) {
        // traversing the words in the current sentence
        // a CoreLabel is a CoreMap with additional token-specific methods
            String prevNeToken = "O";
            String currNeToken = "O";
            boolean newToken = true;
            for (CoreLabel token : sentence.get(CoreAnnotations.TokensAnnotation.class)) {
                currNeToken = token.get(CoreAnnotations.NamedEntityTagAnnotation.class);
                String word = token.get(CoreAnnotations.TextAnnotation.class);        
                String pos = token.get(CoreAnnotations.PartOfSpeechAnnotation.class);
                System.out.println("word:" + word + " currNeToken:" + currNeToken+ " pos:" +pos);
                if (currNeToken.equals("NUMBER")) {
                    continue;
                }
                // Strip out "O"s completely, makes code below easier to understand
                if (currNeToken.equals("O")) {
                    if (pos.startsWith("NN")) {
                        if(pos.equals("NNS")){
                            tags.add(InflectorUtil.getInstance().singularize(word));
                        }else{
                            tags.add(word);
                        }
                    }
                    if (!prevNeToken.equals("O") && (sb.length() > 0)) {
                        log.info("'"+sb.toString()+"' is a "+prevNeToken);
                        tags.add(sb.toString());
                        sb.setLength(0);
                        newToken = true;
                    }
                    continue;
                }


                if (newToken) {
                    prevNeToken = currNeToken;
                    newToken = false;
                    sb.append(word);
                    continue;
                }


                if (currNeToken.equals(prevNeToken)) {
                    sb.append(" " + word);
                } else {
                    log.info("'"+sb.toString()+"' is a "+prevNeToken);
                    tags.add(sb.toString());
                    sb.setLength(0);
                    newToken = true;
                }


                prevNeToken = currNeToken;
            }
            if (!prevNeToken.equals("O") && (sb.length() > 0)) {
                //handleEntity(prevNeToken, sb, tokens);
                log.info("'" + sb.toString() + "' is a " + prevNeToken);
                tags.add(sb.toString());
                sb.setLength(0);
                newToken = true;
            }    
        }
        log.info(tags.toString());
        return tags;
    }

}

################################################    Demo   end  ######################################

################################################    maven dependency  ######################################

<dependency>
            <groupId>edu.stanford.nlp</groupId>
            <artifactId>stanford-corenlp</artifactId>
            <version>3.5.2</version>
            <classifier>models</classifier>
</dependency>

################################################    maven dependency  end ######################################


### Java 中实现与集成自然语言处理 (NLP) 的方法 #### 1. **了解自然语言处理的基础** 自然语言处理(Natural Language Processing, NLP)是计算机科学的一个分支,涉及人工智能和语言学的交叉领域。其目标是让计算机能够理解、解析以及生成人类的语言[^2]。 常见的 NLP 应用场景包括但不限于: - 文本分类:将文档划分为不同的类别。 - 情感分析:评估文本中的情绪倾向。 - 命名实体识别(Named Entity Recognition, NER):提取特定类型的实体名称,如人名、地点等。 - 机器翻译:跨语言转换文本内容。 对于开发者而言,在 Java 中可以利用现有的开源框架来简化 NLP 功能的实现过程。 --- #### 2. **流行的 Java NLP 工具包** 以下是几种广泛使用的 Java NLP 工具包及其特点: ##### a. Stanford CoreNLP Stanford CoreNLP 是由斯坦福大学开发的一套强大的 NLP 软件库,支持多种语言处理任务,例如分词、句法分析、命名实体识别等[^5]。它适用于英语和其他多国语言环境下的复杂文本操作。 安装方式如下所示: ```bash wget http://nlp.stanford.edu/software/stanford-corenlp-full-2022-12-07.zip unzip stanford-corenlp-full-2022-12-07.zip ``` 使用 Maven 配置依赖项时可加入以下片段: ```xml <dependency> <groupId>edu.stanford.nlp</groupId> <artifactId>stanford-corenlp</artifactId> <version>4.5.4</version> </dependency> ``` 调用示例代码: ```java import edu.stanford.nlp.pipeline.*; import java.util.Properties; public class NLPExample { public static void main(String[] args) { Properties props = new Properties(); props.setProperty("annotators", "tokenize,ssplit,pos,lemma"); StanfordCoreNLP pipeline = new StanfordCoreNLP(props); String text = "Your input sentence here."; Annotation document = new Annotation(text); pipeline.annotate(document); // 执行注解流程 System.out.println("--- 输出结果 ---"); for(CoreSentence sent : document.sentences()) { System.out.println(sent.tokens()); // 显示标记化后的单词列表 } } } ``` --- ##### b. Apache OpenNLP Apache OpenNLP 提供了一组基于统计模型的工具集,用于执行诸如句子分割、词性标注等功能[^4]。相比其他选项更加轻量级且易于部署。 Maven 添加依赖声明: ```xml <dependency> <groupId>org.apache.opennlp</groupId> <artifactId>opennlp-tools</artifactId> <version>1.9.4</version> </dependency> ``` 实例演示: ```java import opennlp.tools.tokenize.*; public class TokenizerDemo { public static void main(String[] args)throws Exception{ TokenizerModel model = new TokenizerModel(new FileInputStream("en-token.bin")); Tokenizer tokenizer = new TokenizerME(model); String sentence = "This is an example of tokenization using OpenNLP!"; String tokens[] = tokenizer.tokenize(sentence); System.out.println(java.util.Arrays.toString(tokens)); } } ``` --- #### 3. **构建自定义解决方案** 如果现有工具无法满足需求,则可以通过训练专属的数据模型来自行定制业务逻辑。这通常涉及到收集大量语料资源,并借助深度学习算法完成更高级别的预测工作。 推荐参考资料链接地址:<https://github.com/JohnSnowLabs/spark-nlp> --- #### 4. **总结建议** 针对初学者来说,可以从简单的 API 开始尝试;而对于追求高性能的企业项目则应考虑引入成熟的商业产品或者混合架构设计思路。总之,合理选型才能最大化发挥技术优势[^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值