Funktionierende Textanalyse
parent
dd70508ee0
commit
61bdbc68fb
|
|
@ -0,0 +1,50 @@
|
|||
import java.io.FileNotFoundException;
|
||||
|
||||
/**
|
||||
* Steuert den Ablauf (Eingabe, Verarbeitung, Ausgabe) und ist die einzige
|
||||
* Klasse, die etwas druckt.
|
||||
*/
|
||||
public class Main {
|
||||
|
||||
public static void main(String[] args) {
|
||||
if (args.length != 1) {
|
||||
printError("Aufruf: java -cp out Main <pfad-zur-textdatei>");
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
TextAnalyzer analyzer = new TextAnalyzer(args[0]);
|
||||
|
||||
// 1. Eingabe
|
||||
try {
|
||||
analyzer.loadWords();
|
||||
} catch (FileNotFoundException e) {
|
||||
printError("Datei nicht gefunden: " + args[0]);
|
||||
System.exit(1);
|
||||
}
|
||||
if (analyzer.countWords() == 0) {
|
||||
printError("Die Datei enthält keine Wörter: " + args[0]);
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
// 2. + 3. Verarbeitung (im Analyzer) und Ausgabe
|
||||
printSummary(analyzer);
|
||||
}
|
||||
|
||||
private static void printSummary(TextAnalyzer analyzer) {
|
||||
System.out.println("=== Zusammenfassung ===");
|
||||
System.out.printf("Wörter: %d%n", analyzer.countWords());
|
||||
System.out.printf("Zeichen: %d%n", analyzer.countCharacters());
|
||||
System.out.printf("Ø Wortlänge: %.2f%n", analyzer.averageWordLength());
|
||||
System.out.printf("Häufigstes Wort: %s%n", orDash(analyzer.mostFrequentWords()));
|
||||
System.out.printf("Längstes Wort: %s%n", orDash(analyzer.longestWords()));
|
||||
}
|
||||
|
||||
// Zeigt "-" statt eines leeren Textes (z. B. wenn nur Stoppwörter im Text stehen)
|
||||
private static String orDash(String text) {
|
||||
return text.isEmpty() ? "-" : text;
|
||||
}
|
||||
|
||||
private static void printError(String message) {
|
||||
System.err.println("Fehler: " + message);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,188 @@
|
|||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Scanner;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Lädt eine Textdatei und berechnet Kennzahlen zu ihren Wörtern.
|
||||
* Gibt selbst nichts aus: Alle Ergebnisse werden zurückgegeben, gedruckt wird in Main.
|
||||
*/
|
||||
public class TextAnalyzer {
|
||||
|
||||
private static final String START_MARKER = "*** START OF";
|
||||
private static final String END_MARKER = "*** END OF";
|
||||
// Set.copyOf (statt Set.of) verträgt versehentlich doppelte Einträge
|
||||
private static final Set<String> STOP_WORDS = Set.copyOf(List.of(
|
||||
// Englisch: Artikel, Pronomen, Hilfsverben, Präpositionen, Füllwörter
|
||||
"the", "a", "an", "and", "or", "but", "nor", "so", "yet", "if", "then", "than",
|
||||
"of", "to", "in", "on", "at", "by", "for", "with", "from", "into", "upon", "about",
|
||||
"over", "under", "out", "up", "down", "off", "through", "after", "before", "between",
|
||||
"i", "me", "my", "we", "us", "our", "you", "your", "he", "him", "his", "she", "her",
|
||||
"it", "its", "they", "them", "their", "himself", "herself", "itself", "themselves",
|
||||
"this", "that", "these", "those", "which", "who", "whom", "whose", "what", "when",
|
||||
"where", "why", "how", "there", "here", "one", "all", "any", "some", "no", "not",
|
||||
"only", "other", "such", "own", "same", "too", "very", "just", "now", "also", "again",
|
||||
"more", "most", "much", "many", "each", "both", "few", "once", "while", "because",
|
||||
"as", "is", "am", "are", "was", "were", "be", "been", "being", "do", "did", "does",
|
||||
"have", "has", "had", "will", "would", "can", "could", "may", "might", "shall",
|
||||
"should", "must",
|
||||
// Englisch: Kurzformen ohne Apostroph (don't -> dont)
|
||||
"dont", "didnt", "doesnt", "cant", "couldnt", "wont", "wouldnt", "isnt", "wasnt",
|
||||
"im", "ive", "ill", "youre", "thats", "hes", "shes", "theres",
|
||||
// Deutsch
|
||||
"der", "die", "das", "den", "dem", "des", "ein", "eine", "einen", "einem", "einer",
|
||||
"eines", "und", "oder", "aber", "denn", "weil", "ob", "wenn", "dann", "doch", "so",
|
||||
"ist", "sind", "war", "waren", "bin", "bist", "sein", "seine", "hat", "hatte",
|
||||
"haben", "wird", "werden", "wurde", "kann", "nicht", "kein", "keine", "nur", "noch",
|
||||
"schon", "auch", "sehr", "mehr", "immer", "wieder", "ganz", "da", "hier", "dort",
|
||||
"ich", "du", "er", "sie", "es", "wir", "ihr", "mich", "mir", "ihm", "ihn", "ihnen",
|
||||
"man", "was", "wer", "wo", "wie", "dass", "als", "im", "in", "an", "am", "auf", "aus",
|
||||
"bei", "mit", "nach", "von", "vom", "vor", "zu", "zum", "zur", "für", "um", "durch",
|
||||
"über", "unter", "sich"));
|
||||
|
||||
private final String filePath;
|
||||
private List<String> words = new ArrayList<>(); // bereinigte Wörter, gefüllt durch loadWords()
|
||||
|
||||
public TextAnalyzer(String filePath) {
|
||||
this.filePath = filePath;
|
||||
}
|
||||
|
||||
// ---------- Eingabe ----------
|
||||
|
||||
/**
|
||||
* Liest die Datei mit einem Scanner, schneidet Gutenberg-Header/-Footer ab,
|
||||
* bereinigt die Wörter und speichert sie für die Analyse.
|
||||
*
|
||||
* @throws FileNotFoundException wenn die Datei nicht existiert
|
||||
*/
|
||||
public void loadWords() throws FileNotFoundException {
|
||||
List<String> bookWords = new ArrayList<>(); // Wörter zwischen den Markern
|
||||
List<String> allWords = new ArrayList<>(); // Fallback: Datei ohne Marker
|
||||
boolean insideBook = false;
|
||||
boolean markerFound = false;
|
||||
|
||||
try (Scanner scanner = new Scanner(new File(filePath), StandardCharsets.UTF_8.name())) {
|
||||
while (scanner.hasNextLine()) {
|
||||
String line = scanner.nextLine();
|
||||
if (line.startsWith(START_MARKER)) {
|
||||
insideBook = true;
|
||||
markerFound = true;
|
||||
} else if (line.startsWith(END_MARKER)) {
|
||||
insideBook = false;
|
||||
} else {
|
||||
addWordsOfLine(line, allWords);
|
||||
if (insideBook) {
|
||||
addWordsOfLine(line, bookWords);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
words = cleanWords(markerFound ? bookWords : allWords);
|
||||
}
|
||||
|
||||
private void addWordsOfLine(String line, List<String> target) {
|
||||
for (String word : line.trim().split("\\s+")) {
|
||||
if (!word.isEmpty()) {
|
||||
target.add(word);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Kleinbuchstaben, Satzzeichen weg, durch Bindestriche/Gedankenstriche verbundene Wörter werden getrennt. */
|
||||
private List<String> cleanWords(List<String> rawWords) {
|
||||
List<String> cleanedWords = new ArrayList<>();
|
||||
for (String rawWord : rawWords) {
|
||||
String cleaned = rawWord.toLowerCase()
|
||||
.replace("-", " ") // Bindestrich und "--": Wort-Wort -> Wort Wort
|
||||
.replace("—", " ") // langer Gedankenstrich
|
||||
.replace("–", " ") // mittellanger Gedankenstrich
|
||||
.replaceAll("[,.;:!?\"'’]", "");
|
||||
for (String part : cleaned.split("\\s+")) {
|
||||
if (!part.isEmpty()) {
|
||||
cleanedWords.add(part);
|
||||
}
|
||||
}
|
||||
}
|
||||
return cleanedWords;
|
||||
}
|
||||
|
||||
// ---------- Verarbeitung ----------
|
||||
|
||||
public int countWords() {
|
||||
return words.size();
|
||||
}
|
||||
|
||||
public int countCharacters() {
|
||||
int total = 0;
|
||||
for (String word : words) {
|
||||
total += word.length();
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
/** Durchschnittliche Wortlänge; 0.0 bei leerer Wortliste (keine Division durch 0). */
|
||||
public double averageWordLength() {
|
||||
if (words.isEmpty()) {
|
||||
return 0.0;
|
||||
}
|
||||
return (double) countCharacters() / countWords();
|
||||
}
|
||||
|
||||
public Map<String, Integer> countWordFrequencies() {
|
||||
Map<String, Integer> frequencies = new HashMap<>();
|
||||
for (String word : words) {
|
||||
frequencies.merge(word, 1, Integer::sum);
|
||||
}
|
||||
return frequencies;
|
||||
}
|
||||
|
||||
/** Häufigste Wörter ohne Stoppwörter; bei Gleichstand alle, Format "wort1, wort2: anzahl". */
|
||||
public String mostFrequentWords() {
|
||||
Map<String, Integer> counts = new HashMap<>();
|
||||
for (Map.Entry<String, Integer> entry : countWordFrequencies().entrySet()) {
|
||||
if (!STOP_WORDS.contains(entry.getKey())) {
|
||||
counts.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
return findHighest(counts);
|
||||
}
|
||||
|
||||
/** Längste Wörter; bei Gleichstand alle, Format "wort1, wort2: länge". */
|
||||
public String longestWords() {
|
||||
Map<String, Integer> lengths = new HashMap<>();
|
||||
for (String word : countWordFrequencies().keySet()) { // keySet: jedes Wort nur einmal
|
||||
lengths.put(word, word.length());
|
||||
}
|
||||
return findHighest(lengths);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sucht den höchsten Wert und sammelt alle Wörter, die ihn haben.
|
||||
* Gibt "wort1, wort2: wert" zurück, bei leerer Map einen leeren String.
|
||||
*/
|
||||
private String findHighest(Map<String, Integer> valueByWord) {
|
||||
List<String> bestWords = new ArrayList<>();
|
||||
int highestValue = 0;
|
||||
|
||||
for (Map.Entry<String, Integer> entry : valueByWord.entrySet()) {
|
||||
if (entry.getValue() > highestValue) {
|
||||
bestWords.clear(); // neuer Höchstwert: bisherige Wörter verwerfen
|
||||
bestWords.add(entry.getKey());
|
||||
highestValue = entry.getValue();
|
||||
} else if (entry.getValue() == highestValue) {
|
||||
bestWords.add(entry.getKey()); // Gleichstand: Wort dazunehmen
|
||||
}
|
||||
}
|
||||
if (bestWords.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
Collections.sort(bestWords); // alphabetisch, damit die Ausgabe immer gleich ist
|
||||
return String.join(", ", bestWords) + ": " + highestValue;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
|
||||
public static void main(String[] args) {
|
||||
System.out.println("Hello World!");
|
||||
}
|
||||
Loading…
Reference in New Issue