我使用以下代码(使用 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/