写一段对单条文本分词并提取关键字的代码示例,用java语言
时间: 2024-02-01 15:15:56 浏览: 34
以下是使用Java语言对一段文本进行分词和提取关键字的示例代码:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
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;
public class KeywordExtractor {
public static List<String> extractKeywords(String text) {
Properties props = new Properties();
props.setProperty("annotators", "tokenize, ssplit, pos");
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
Annotation document = new Annotation(text);
pipeline.annotate(document);
List<String> keywords = new ArrayList<String>();
List<CoreMap> sentences = document.get(CoreAnnotations.SentencesAnnotation.class);
for (CoreMap sentence : sentences) {
for (CoreLabel token : sentence.get(CoreAnnotations.TokensAnnotation.class)) {
String pos = token.get(CoreAnnotations.PartOfSpeechAnnotation.class);
if (pos.startsWith("NN")) {
keywords.add(token.originalText());
}
}
}
return keywords;
}
public static void main(String[] args) {
String text = "The quick brown fox jumped over the lazy dog.";
List<String> keywords = extractKeywords(text);
System.out.println(keywords);
}
}
```
该示例代码使用了Stanford CoreNLP库进行文本分析,其中包括对文本进行分词和词性标注。在提取关键字的过程中,我们只考虑名词(NN)作为关键字,并将它们添加到一个列表中返回。在示例代码中,我们使用了一个简单的文本作为输入,但是在实际应用中,您可以将任何文本作为输入,并获得它的关键字列表。