我有一个代码,可以计算文件中的单词出现次数。我想在2个文件中使用它,并在分离的表中显示recurrent(两个文件都包含)单词。您有什么想法,如何将它与2个文件一起使用?
while ((inputLine = bufferedReader.readLine()) != null) {
String[] words = inputLine.split("[ \n\t\r.,;:!?(){}]");
for (int counter = 0; counter < words.length; counter++) {
String key = words[counter].toLowerCase();
if (key.length() > 0) {
if (crunchifyMap.get(key) == null) {
crunchifyMap.put(key, 1);
} else {
int value = crunchifyMap.get(key).intValue();
value++;
crunchifyMap.put(key, value);
}
}
}
}
Set<Map.Entry<String, Integer>> entrySet = crunchifyMap.entrySet();
System.out.println("Words" + "\t\t" + "# of Occurances");
for (Map.Entry<String, Integer> entry : entrySet) {
System.out.println(entry.getKey() + "\t\t" + entry.getValue());
}
答案 0 :(得分:2)
您应该使用以下(非常粗略)算法:
Set words
; Set words2
; words
中words2
中包含的所有字词来计算相交集:words.retainAll(words2)
words
包含您的最终列表。请注意,如果将其放入类似
的方法中,则可以重复使用文件读取算法public Set<String> readWords(Reader reader) {
....
}
计算出现次数
如果您还想知道发生的频率,您应该将每个文件读入Map<String, Integer>
,将每个单词映射到该文件中出现的频率。
新的Map.merge(...)
函数(自Java 8起)简化了计数:
Map<String, Integer> freq = new HashMap<>();
for(String word : words) {
// insert 1 or increment already mapped value
freq.merge(word, 1, Integer::sum);
}
然后应用以下略微修改的算法:
Map wordsFreq1
; Map wordsFreq2
; Set<String> words = wordsFreq1.keySet()
words.retainAll(wordsFreq2.keySet())
words
包含所有相同的字词,wordsFreq1
和wordsFreq2
包含两个文件的所有字词的频率。通过这三种数据结构,您可以轻松获得所需的所有信息。例如:
Map<String, Integer> wordsFreq1 = ... // read from file
Map<String, Integer> wordsFreq2 = ... // read from file
Set<String> commonWords = new HashSet<>(wordsFreq1.keySet());
commonWords.retainAll(wordsFreq2.keySet());
// Map that contains the summarized frequencies of all words
Map<String, Integer> allWordsTotalFreq = new HashMap<>(wordsFreq1);
wordsFreq2.forEach((word, freq) -> allWordsTotalFreq.merge(word, freq, Integer::sum));
// Map that contains the summarized frequencies of words in common
Map<String, Integer> commonWordsTotalFreq = new HashMap<>(allWordsTotalFreq);
commonWordsTotalFreq.keySet().retainAll(commonWords);
// List of common words sorted by frequency:
List<String> list = new ArrayList<>(commonWords);
Collections.sort(list, Comparator.comparingInt(commonWordsTotalFreq::get).reversed());
答案 1 :(得分:0)
使用类似的代码读取第二个文件,并在上一个文件的地图中找到它:
while ((inputLine = bufferedReader.readLine()) != null) {
String[] words = inputLine.split("[ \n\t\r.,;:!?(){}]");
for (int counter = 0; counter < words.length; counter++) {
String key = words[counter].toLowerCase();
if (key.length() > 0) {
if (crunchifyMap.get(key) == null) {
continue;
} else if(duplicateMap.get(key) == null) {
duplicateMap.put(key, 1);
}
}
}
}
Set<Map.Entry<String, Integer>> duplicateEntrySet = duplicateMap.entrySet();
System.out.println("Duplicate words:");
for (Map.Entry<String, Integer> entry : duplicateEntrySet ) {
System.out.println(entry.getKey());
}
}