AuthorDetector/src/main/java/de/nicode3141/genredct/GenreData.java

181 lines
6.5 KiB
Java

package de.nicode3141.genredct;
import de.nicode3141.utils.CSV;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class GenreData {
/**
* This method gets all books and their corresponding label
* @param csvPath Path of the labels.csv file
* @return Map key: genre, value: paths
*/
public static Map<String, List<String>> loadGenres(String csvPath){
try{
// TODO: Loop thru all paths and return a Map of <label, paths>
Scanner scanner = new Scanner(new File(csvPath), "UTF-8");
Map<String, List<String>> genrePaths = new HashMap<>();
scanner.nextLine(); // Skip Header
while(scanner.hasNextLine()){
String line = scanner.nextLine();
List<String> tokens = CSV.splitCsv(line);
if(tokens.size() < 8) continue;
String genre = tokens.get(3);
String path = tokens.get(7);
genrePaths.computeIfAbsent(genre, oldPaths -> new ArrayList<>()).add(path);
}
scanner.close();
return genrePaths;
}
catch(FileNotFoundException e){
IO.println(e.toString());
return null;
}
}
/**
* Counts top X words of all textfiles
* @param paths source plain textfiles
* @param limit only counts the top (limit) words
* @param skipWords number of first words to skip
* @return LinkedMap key: word, value: count
*/
public static Set<String> createAlphabet(List<String> paths, int limit, int skipWords){
// TODO: Scan texts line by line and count already added Words.
// If word was not present, add it to the Map.
Map<String, Integer> allWords = new HashMap<>();
for(String path : paths){
try{
Scanner scanner = new Scanner(new File(path), "UTF-8");
boolean startCounting = false;
while(scanner.hasNextLine()){
String line = scanner.nextLine();
if(!startCounting){
if(line.contains("*** START OF THE PROJECT GUTENBERG EBOOK")){
startCounting = true;
}
continue;
}
Scanner lineScanner = new Scanner(line);
while(lineScanner.hasNext()){
String word = lineScanner.next().toLowerCase();
// Removes all non Unicode chars
// Source - https://stackoverflow.com/a/43214777
word = word.replaceAll("[^\\p{L}]", "");
if(word.isEmpty()) continue;
allWords.put(word, allWords.getOrDefault(word, 0) +1);
}
lineScanner.close();
}
scanner.close();
} catch(FileNotFoundException e){
IO.println("Couldn't find file " + path + " err: " + e.getLocalizedMessage());
}
}
// After that, sort the Map. Simple with ArrayList sort()
// The ArrayList could contain the entrySet of the Map
// Then loop thru the sorted ArrayList, maximum (limit) and create a new Map
// LinkedHashMap would make sense here, because of the ordering
List<Map.Entry<String, Integer>> entries = new ArrayList<>(allWords.entrySet());
entries.sort((a, b) -> {
// compared > 0 -> b > a; < 0 -> b < a; 0 b == a
int compared = Integer.compare(b.getValue(), a.getValue());
return compared != 0 ? compared : a.getKey().compareTo(b.getKey()); // Sort by biggest, when same by ABC
});
Set<String> topWords = new LinkedHashSet<>();
for(int i = skipWords; i < Math.min(limit + skipWords, entries.size()); i++){
topWords.add(entries.get(i).getKey());
}
return topWords;
}
/**
* Counts all words against the common vocab and categorizes them to their genre.
* @param texts label, path of the genre texts
* @param vocabulary common top X words to count against
* @return Map key: genre, value: TextCounts
*/
public static Map<String, List<TextCounts>> countTrainData(Map<String, List<String>> texts, Set<String> vocabulary){
Map<String, List<TextCounts>> genreWordCounts = new LinkedHashMap<>();
// Loop thru each genre
for(Map.Entry<String, List<String>> textPaths : texts.entrySet()){
List<TextCounts> genreTextCount = new ArrayList<>();
// Loop thru all Texts
for(String textPath : textPaths.getValue()){
try {
Scanner scanner = new Scanner(new File(textPath), "UTF-8");
TextCounts textWordCount = countCommonWords(scanner, vocabulary);
genreTextCount.add(textWordCount);
} catch (FileNotFoundException err){
IO.print(err.getLocalizedMessage());
}
}
genreWordCounts.put(textPaths.getKey(), genreTextCount);
}
return genreWordCounts;
}
/**
* Counts top X words which are in the vocabulary of a textfile
* @param scanner source plain textfile/input
* @param vocabulary words to count
* @return TextCounts -> LinkedMap key: word, value: count; totalWords
*/
public static TextCounts countCommonWords(Scanner scanner, Set<String> vocabulary){
// TODO: Scan text line by line and count words from vocabulary.
Map<String, Integer> vocabCount = new LinkedHashMap<>();
int totalWords = 0;
for(String item : vocabulary){
vocabCount.put(item, 0);
}
try {
while(scanner.hasNext()){
String word = scanner.next().toLowerCase();
// Removes all non Unicode chars
// Source - https://stackoverflow.com/a/43214777
word = word.replaceAll("[^\\p{L}]", "");
if(word.isEmpty()) continue;
totalWords++;
// If word matches vocabulary
if(vocabCount.containsKey(word)){
vocabCount.put(word, vocabCount.get(word) +1);
}
}
scanner.close();
} catch (Exception e){
IO.println("Couldn't close scanner");
}
return new TextCounts(vocabCount, totalWords);
}
}