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> loadGenres(String csvPath){ try{ // TODO: Loop thru all paths and return a Map of Scanner scanner = new Scanner(new File(csvPath), "UTF-8"); Map> genrePaths = new HashMap<>(); scanner.nextLine(); // Skip Header while(scanner.hasNextLine()){ String line = scanner.nextLine(); List 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 createAlphabet(List 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 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> 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 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> countTrainData(Map> texts, Set vocabulary){ Map> genreWordCounts = new LinkedHashMap<>(); // Loop thru each genre for(Map.Entry> textPaths : texts.entrySet()){ List 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 vocabulary){ // TODO: Scan text line by line and count words from vocabulary. Map 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); } }