Markovify is a simple, extensible Markov chain generator. Right now, its main use is for building Markov models of large corpora of text, and generating random sentences from that. But, in theory, it could be used for other applications.
Simplicity. "Batteries included," but it's easy to override key methods.
Models can be stored as JSON, allowing you to cache your results and save them for later.
Text parsing and sentence generation methods are highly extensible, allowing you to set your own rules.
Relies only on pure-Python libraries, and very few of them.
Tested on Python 2.7, 3.4, 3.5, and 3.6.
pip install markovify
import markovify # Get raw text as string. with open("/path/to/my/corpus.txt") as f: text = f.read() # Build the model. text_model = markovify.Text(text) # Print five randomly-generated sentences for i in range(5): print(text_model.make_sentence()) # Print three randomly-generated sentences of no more than 140 characters for i in range(3): print(text_model.make_short_sentence(140))
The usage examples here assume you're trying to markovify text. If you'd like to use the underlying
markovify.Chainclass, which is not text-specific, check out the (annotated) source code.
Markovify works best with large, well-punctuated texts. If your text doesn't use
.s to delineate sentences, put each sentence on a newline, and use the
markovify.NewlineTextclass instead of
If you've accidentally read your text as one long sentence, markovify will be unable to generate new sentences from it due to a lack of beginning and ending delimiters. This can happen if you've read a newline delimited file using the
markovify.Textcommand instead of
markovify.NewlineText. To check this, the command
[key for key in txt.chain.model.keys() if "___BEGIN__" in key]command will return all of the possible sentence starting words, and should return more than one result.
By default, the
make_sentencemethod tries, a maximum of 10 times per invocation, to make a sentence that doesn't overlap too much with the original text. If it is successful, the method returns the sentence as a string. If not, it returns
None. To increase or decrease the number of attempts, use the
trieskeyword argument, e.g., call
markovify.Texttries to generate sentences that don't simply regurgitate chunks of the original text. The default rule is to suppress any generated sentences that exactly overlaps the original text by 15 words or 70% of the sentence's word count. You can change this rule by passing
make_sentencemethod. Alternatively you can disable this check entirely by passing
Specifying the model's state size
markovify.Text uses a state size of 2. But you can instantiate a model with a different state size. E.g.,:
text_model = markovify.Text(text, state_size=3)
markovify.combine(...), you can combine two or more Markov chains. The function accepts two arguments:
models: A list of
markovifyobjects to combine. Can be instances of
markovify.Text(or their subclasses), but all must be of the same type.
weights: Optional. A list — the exact length of
models— of ints or floats indicating how much relative emphasis to place on each source. Default:
[ 1, 1, ... ].
model_a = markovify.Text(text_a) model_b = markovify.Text(text_b) model_combo = markovify.combine([ model_a, model_b ], [ 1.5, 1 ])
... would combine
model_b, but place 50% more weight on the connections from
markovify.Text class is highly extensible; most methods can be overridden. For example, the following
POSifiedText class uses NLTK's part-of-speech tagger to generate a Markov model that obeys sentence structure better than a naive model. (It works. But be warned:
pos_tag is very slow.)
import markovify import nltk import re class POSifiedText(markovify.Text): def word_split(self, sentence): words = re.split(self.word_split_pattern, sentence) words = [ "::".join(tag) for tag in nltk.pos_tag(words) ] return words def word_join(self, words): sentence = " ".join(word.split("::") for word in words) return sentence
The most useful
markovify.Text models you can override are:
For details on what they do, see the (annotated) source code.
It can take a while to generate a Markov model from a large corpus. Sometimes you'll want to generate once and reuse it later. To export a generated
markovify.Text model, use
my_text_model.to_json(). For example:
corpus = open("sherlock.txt").read() text_model = markovify.Text(corpus, state_size=3) model_json = text_model.to_json() # In theory, here you'd save the JSON to disk, and then read it back later. reconstituted_model = markovify.Text.from_json(model_json) reconstituted_model.make_short_sentence(140) >>> 'It cost me something in foolscap, and I had no idea that he was a man of evil reputation among women.'
You can also export the underlying Markov chain on its own — i.e., excluding the original corpus and the
state_size metadata — via
Markovify In The Wild
- BuzzFeed's Tom Friedman Sentence Generator / @mot_namdeirf.
- UserSim, which powers /u/user_simulator bot on Reddit and generates comments based on a user's comment history.
- SubredditSimulator, which generates random Reddit submissions and comments based on a subreddit's previous activity.
- college crapplication, a web-app that generates college application essays. [code]
- @MarkovPicard, a Twitter bot based on Star Trek: The Next Generation transcripts. [code]
- sekrits.herokuapp.com, a
markovify-powered quiz that challenges you to tell the difference between "two file titles relating to matters of [Australian] national security" — one real and one fake. [code]
- Hacker News Simulator, which does what it says on the tin. [code]
- Stak Attak, a "poetic stackoverflow answer generator." [code]
- MashBOT, a
markovify-powered Twitter bot attached to a printer. Presented by Helen J Burgess at Babel Toronto 2015. [code]
- The Mansfield Reporter, "a simple device which can generate new text from some of history's greatest authors [...] running on a tiny Raspberry Pi, displaying through a tft screen from Adafruit."
- twitter markov, a tool to "create markov chain ("_ebooks") accounts on Twitter."
- @Bern_Trump_Bot, "Bernie Sanders and Donald Trump driven by Markov Chains." [code]
- @RealTrumpTalk, "A bot that uses the things that @realDonaldTrump tweets to create it's own tweets." [code]
- Taylor Swift Song Generator, which does what it says. [code]
- @BOTtalks / ideasworthautomating.com. "TIM generates talks on a broad spectrum of topics, based on the texts of slightly more coherent talks given under the auspices of his more famous big brother, who shall not be named here." [code]
- Internal Security Zones, "Generative instructions for prison design & maintenance." [code]
- Miraculous Ladybot. Generates Miraculous Ladybug fanfictions and posts them on Tumblr. [code]
- @HaikuBotto, "I'm a bot that writes haiku from literature. beep boop" [code]
- Chat Simulator Bot, a bot for Telegram. [code]
- emojipasta.club, "a web service that exposes RESTful endpoints for generating emojipastas, as well as a simple frontend for generating and tweeting emojipasta sentences." [code]
- Towel Generator, "A system for generating sentences similar to those from the hitchhikers series of books." [code]
- @mercurialbot, "A twitter bot that generates tweets based on its mood." [code]
- becomeacurator.com, which "generates curatorial statements for contemporary art expositions, using Markov chains and texts from galleries around the world." [code]
- mannynotfound/interview-bot, "A python based terminal prompt app to automate the interview process."
- Steam Game Generator, which "uses data from real Steam games, randomized using Markov chains." [code]
- @DicedOnionBot, which "generates new headlines by The Onion by regurgitating and combining old headlines." [code]
- @thought__leader, "Thinking thoughts so you don't have to!" [blog post]
- @_murakamibot and @jamesjoycebot, bots that tweet Haruki Murakami and James Joyce-like sentences. [code]
- shartificialintelligence.com, "the world's first creative ad agency staffed entirely with copywriter robots." [code]
- @NightValeFeed, which "generates tweets by combining @NightValeRadio tweets with @BuzzFeed headlines." [code]
- Wynbot9000, which "mimics your friends on Google Hangouts." [code]
- @sealDonaldTrump, "a twitter bot that sounds like @realDonaldTrump, with an aquatic twist." [code]
- @veeceebot, which is "like VCs but better!" [code]
- @mar_phil_bot, a Twitter bot trained on Nietzsche, Russell, Kant, Machiavelli, and Plato. [code]
Have other examples? Pull requests welcome.
Many thanks to the following GitHub users for contributing code and/or ideas:
Developed at BuzzFeed.