Java解析Word文档关键词计数:代码示例和优化
以下是使用Java解析Word文档中关键词的代码示例,并进行了优化:
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class WordKeywordsCounter {
public static void main(String[] args) {
String filePath = "path/to/your/word/document.docx";
String text = extractTextFromWord(filePath);
int keywordCount = countKeywords(text);
System.out.println("关键词个数:" + keywordCount);
}
private static String extractTextFromWord(String filePath) {
try {
FileInputStream fis = new FileInputStream(filePath);
XWPFDocument doc = new XWPFDocument(fis);
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
return extractor.getText();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
private static int countKeywords(String text) {
String[] keywords = text.split("[,;\s]{2,}");
Set<String> uniqueKeywords = new HashSet<>(Arrays.asList(keywords));
return uniqueKeywords.size();
}
}
优化说明:
- 代码中使用了Apache POI库来提取Word文档的文本内容。在运行代码之前,请确保已将
poi和poi-ooxml库添加到项目的依赖中。 filePath变量需要替换为你的Word文档的实际路径。- 关键词的分割使用了正则表达式
[,;\s]{2,},该表达式表示逗号、分号或至少两个空格用作关键词的分隔符。如果你的关键词分隔符不同,请相应地修改该正则表达式。 - 代码中使用了
HashSet来去重,确保统计结果只包含唯一的关键词。
运行代码后,将打印出关键词的个数。
希望对您有所帮助!
原文地址: https://www.cveoy.top/t/topic/o26v 著作权归作者所有。请勿转载和采集!