From c1fd9e8c4b2682dee10cebd8ce4927fba8d1e65e Mon Sep 17 00:00:00 2001 From: nicode3141 Date: Thu, 12 Nov 2026 22:24:23 +0100 Subject: [PATCH] (detector): implemented GenreData functions, created CSV Helper class --- .../de/nicode3141/genredct/GenreData.java | 111 +++++++++++++++++- src/main/java/de/nicode3141/utils/CSV.java | 36 ++++++ src/test/java/genredct/DetectorTests.java | 22 ++++ 3 files changed, 163 insertions(+), 6 deletions(-) create mode 100644 src/main/java/de/nicode3141/utils/CSV.java diff --git a/src/main/java/de/nicode3141/genredct/GenreData.java b/src/main/java/de/nicode3141/genredct/GenreData.java index c44f99a..e71a69f 100644 --- a/src/main/java/de/nicode3141/genredct/GenreData.java +++ b/src/main/java/de/nicode3141/genredct/GenreData.java @@ -1,7 +1,10 @@ package de.nicode3141.genredct; -import java.util.List; -import java.util.Map; +import de.nicode3141.utils.CSV; + +import java.io.File; +import java.io.FileNotFoundException; +import java.util.*; public class GenreData { @@ -11,8 +14,32 @@ public class GenreData { * @return Map key: genre, value: paths */ public static Map> loadGenres(String csvPath){ - // TODO: Loop thru all paths and return a Map of - return null; + 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; + } } /** @@ -31,14 +58,65 @@ public class GenreData { * @param limit only counts the top (limit) words * @return LinkedMap key: word, value: count */ - public static Map countWords(String[] paths, int limit){ + public static Map countWords(List paths, int limit){ // 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 - return null; + + 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 + }); + + Map topWords = new LinkedHashMap<>(); + for(int i = 0; i < Math.min(limit, entries.size()); i++){ + topWords.put(entries.get(i).getKey(), entries.get(i).getValue()); + } + + return topWords; } /** @@ -49,6 +127,27 @@ public class GenreData { */ public static Map countCommonWords(String path, String[] vocabulary){ // TODO: Scan text line by line and count words from vocabulary. + + try { + Scanner scanner = new Scanner(new File(path), "UTF-8"); + + 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; + + // If word matches vocabulary + + } + scanner.close(); + + } catch (FileNotFoundException e) { + IO.println("Couldn't find file " + path + " err: " + e.getLocalizedMessage()); + } + return null; } } diff --git a/src/main/java/de/nicode3141/utils/CSV.java b/src/main/java/de/nicode3141/utils/CSV.java new file mode 100644 index 0000000..4557477 --- /dev/null +++ b/src/main/java/de/nicode3141/utils/CSV.java @@ -0,0 +1,36 @@ +package de.nicode3141.utils; + +import java.util.ArrayList; +import java.util.List; + +public class CSV { + /** + * Splits a csv line into the tokens + * @param line a csv line + * @return list of tokens + */ + public static List splitCsv(String line) { + List out = new ArrayList<>(); + StringBuilder sb = new StringBuilder(); + boolean inQuotes = false; + + for (int i = 0; i < line.length(); i++) { + char c = line.charAt(i); + if (c == '"') { + if (inQuotes && i + 1 < line.length() && line.charAt(i + 1) == '"') { + sb.append('"'); + i++; + } else { + inQuotes = !inQuotes; + } + } else if (c == ',' && !inQuotes) { + out.add(sb.toString()); + sb.setLength(0); + } else { + sb.append(c); + } + } + out.add(sb.toString()); + return out; + } +} diff --git a/src/test/java/genredct/DetectorTests.java b/src/test/java/genredct/DetectorTests.java index c2dc9ba..eedfb09 100644 --- a/src/test/java/genredct/DetectorTests.java +++ b/src/test/java/genredct/DetectorTests.java @@ -1,10 +1,12 @@ package genredct; import de.nicode3141.genredct.Detector; +import de.nicode3141.genredct.GenreData; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.HashMap; +import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -28,4 +30,24 @@ public class DetectorTests { double sum = -0.11d; assertEquals(sum, Detector.calcSum(wordCounts, weigths, bias)); } + + @DisplayName("Loads Genres") + @Test + public void testGenresLoad(){ + GenreData.loadGenres("data/labels.csv"); + } + + @DisplayName("Count All Words") + @Test + public void testLoadAllWords(){ + Map> genreData = GenreData.loadGenres("data/labels.csv"); + List allPaths = genreData.values() + .stream() + .flatMap(List::stream) + .toList(); + + System.out.println("Genres: " + genreData.size()); + System.out.println("Total paths: " + allPaths); + Map vocabulary = GenreData.countWords(allPaths, 500); + } }