Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

// Title: Markov.

java
//Author: Alexandra Comaduran
//Abstract: Markov.java is a Java program that implements
// a Markov chain for text generation. It reads from text
// files to create a model of word sequences and then
// generates new, stylistically similar sentences based on
// this model.
//Date: 11/14/23

package org.example;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;

public class Markov {


public static final String BEGINS_SENTENCE = "__$";
public static final String PUNCTUATION_MARKS = ".!?";
private String prevWord = BEGINS_SENTENCE;
private HashMap<String, ArrayList<String>> words = new HashMap<>();

public Markov() {
words.put(BEGINS_SENTENCE, new ArrayList<>());
}

public HashMap<String, ArrayList<String>> getWords() {


return words;
}

public void addFromFile(String filename) {


try {
Files.lines(Paths.get(filename)).forEach(this::addLine);
} catch (IOException e) {
e.printStackTrace();
}
}

public void addLine(String line) {


String trimmedLine = line.trim();
if (trimmedLine.isEmpty()) return;
String[] splitWords = trimmedLine.split("\\s+");
for (String word : splitWords) {
addWord(word);
}
}

public void addWord(String word) {


words.putIfAbsent(prevWord, new ArrayList<>());
words.get(prevWord).add(word);

if (endsWithPunctuation(word)) {
prevWord = BEGINS_SENTENCE;
} else {
prevWord = word;
}
}
public static boolean endsWithPunctuation(String word) {
return word.length() > 0 &&
PUNCTUATION_MARKS.contains(word.substring(word.length() - 1));
}

public String getSentence() {


StringBuilder sentence = new StringBuilder();
String currentWord = randomWord(BEGINS_SENTENCE);
while (currentWord != null) {
sentence.append(currentWord).append(" ");
if (endsWithPunctuation(currentWord)) {
break;
}
currentWord = randomWord(currentWord);
}
return sentence.toString().trim();
}

public String randomWord(String key) {


ArrayList<String> wordList = words.get(key);
if (wordList == null || wordList.isEmpty()) {
return null;
}
return wordList.get(new Random().nextInt(wordList.size()));
}

@Override
public String toString() {
return words.toString();
}
}

You might also like