java - 如何从使用tika提取的文本中获取频繁出现的词

标签 java file apache-tika word-frequency

我使用以下代码(使用 tika)提取了多种文件格式(pdf、html、doc)的文本

File file1 = new File("c://sample.pdf);
InputStream input = new FileInputStream(file1); 
BodyContentHandler handler = new BodyContentHandler(10*1024*1024);
JSONObject obj = new JSONObject();
obj.put("Content",handler.toString());

现在我的要求是从提取的内容中获取频繁出现的词,你能建议我怎么做吗?

谢谢

最佳答案

这是最常用词的函数。

需要将内容传递给函数,得到频繁出现的词。

String getMostFrequentWord(String input) {
    String[] words = input.split(" ");
    // Create a dictionary using word as key, and frequency as value
    Map<String, Integer> dictionary = new HashMap<String, Integer>();
    for (String word : words) {
        if (dictionary.containsKey(word)) {
            int frequency = dictionary.get(word);
            dictionary.put(word, frequency + 1);
        } else {
            dictionary.put(word, 1);
        }
    }

    int max = 0;
    String mostFrequentWord = "";
    Set<Entry<String, Integer>> set = dictionary.entrySet();
    for (Entry<String, Integer> entry : set) {
        if (entry.getValue() > max) {
            max = entry.getValue();
            mostFrequentWord = entry.getKey();
        }
    }

    return mostFrequentWord;
}

算法是 O(n),所以性能应该没问题。

关于java - 如何从使用tika提取的文本中获取频繁出现的词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17440330/

相关文章:

c# - 分布式应用程序,密码哈希

java - Hibernate orphanRemoval是否可以在唯一的约束下工作?

java - OpenCV 常量.CaptureProperty

file - 付款后直接创建带有链接的自定义 Paypal 按钮

使用 Apache Tika 库编译 Java 程序 - 依赖项

java - 在 Java 中使用 Apache Tika 进行解析时,PDF 项目符号以问号形式出现

java - 如何选择用于移动应用程序的服务器技术堆栈?

ios - Swift 中的持久化文件

java - 解析文件时出错——运行时错误

java - 从字节数组中获取文件名