A Python module for generating text with Markov chains
Clone the GitHub repository to your local machine:
git clone https://github.com/ArloMichael/OpenMarkov.git- Import the
Chainclass from the module:
from markov import Chain- Create an instance of the
Chainclass with an optionalorderparameter to specify the order of the Markov chain (default is 1):
chain = Chain(order=2)- Train the Markov chain by providing a text corpus using the
trainmethod:
text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce interdum orci vitae massa efficitur finibus. Nunc nulla massa, malesuada elementum porta at, blandit et erat. Vivamus auctor vehicula libero nec ornare. Donec in eros nulla. Cras a interdum dolor, at viverra enim. Nam cursus nunc dignissim, blandit ex id, commodo tellus. Integer fringilla tortor id tellus egestas vehicula."
chain.train(text)- Generate text using the
generatemethod. Specify the desired length of the generated text with thelengthparameter (default is 10). You can also provide an optionalseedparameter to set the initial prefix:
generated_text = chain.generate(length=20, seed="Lorem ipsum")
print(generated_text)- Save the trained Markov chain to a JSON file using the
savemethod:
chain.save("model.json")- Load a saved Markov chain from a JSON file using the
loadclass method:
chain = Chain.load("model.json")Here's a complete example demonstrating the usage of the Markov chain text generator:
from markov import Chain
# Create an instance of the Chain class
chain = Chain(order=2)
# Train the Markov chain
text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed lacinia augue vitae consequat fermentum."
chain.train(text)
# Generate text
generated_text = chain.generate(length=20, seed="Lorem ipsum")
print(generated_text)
# Save the Markov chain
chain.save("model.json")
# Load a saved Markov chain
loaded_chain = Chain.load("model.json")