Package: markovify
MarkovifyMarkovify is a simple, extensible Markov chain generator. Right now, its primary use is for building Markov models of large corpora of text and generating random sentences from that. However, in theory, it could be used forother applications.Why Markovify?InstallationBasic UsageAdvanced UsageMarkovify In The WildThanksWhy Markovify?Some reasons:Simplicity. "Batteries included," but it is 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 3.6, 3.7, 3.8, and 3.9.Installationpip install markovifyBasic Usageimportmarkovify# Get raw text as string.withopen("/path/to/my/corpus.txt")asf:text=f.read()# Build the model.text_model=markovify.Text(text)# Print five randomly-generated sentencesforiinrange(5):print(text_model.make_sentence())# Print three randomly-generated sentences of no more than 280 charactersforiinrange(3):print(text_model.make_short_sentence(280))Notes:The usage examples here assume you are trying to markovify text. If you would like to use the underlyingmarkovify.Chainclass, which is not text-specific, check outthe (annotated) source code.Markovify works best with large, well-punctuated texts. If your text does not use.s to delineate sentences, put each sentence on a newline, and use themarkovify.NewlineTextclass instead ofmarkovify.Textclass.If you have accidentally read the input 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 issue can occur if you have read a newline delimited file using themarkovify.Textcommand instead ofmarkovify.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, themake_sentencemethod tries a maximum of 10 times per invocation, to make a sentence that does not overlap too much with the original text. If it is successful, the method returns the sentence as a string. If not, it returnsNone. To increase or decrease the number of attempts, use thetrieskeyword argument, e.g., call.make_sentence(tries=100).By default,markovify.Texttries to generate sentences that do not 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 passingmax_overlap_ratioand/ormax_overlap_totalto themake_sentencemethod. Alternatively, this check can be disabled entirely by passingtest_outputas False.Advanced UsageSpecifying the model's state sizeState size is a number of words the probability of a next word depends on.By default,markovify.Textuses 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)Combining modelsWithmarkovify.combine(...), you can combine two or more Markov chains. The function accepts two arguments:models: A list ofmarkovifyobjects to combine. Can be instances ofmarkovify.Chainormarkovify.Text(or their subclasses), but all must be of the same type.weights: Optional. A list — the exact length ofmodels— of ints or floats indicating how much relative emphasis to place on each source. Default:[ 1, 1, ... ].For instance:model_a=markovify.Text(text_a)model_b=markovify.Text(text_b)model_combo=markovify.combine([model_a,model_b],[1.5,1])This code snippet would combinemodel_aandmodel_b, but, it would also place 50% more weight on the connections frommodel_a.Compiling a modelOnce a model has been generated, it may also be compiled for improved text generation speed and reduced size.text_model=markovify.Text(text)text_model=text_model.compile()Models may also be compiled in-place:text_model=markovify.Text(text)text_model.compile(inplace=True)Currently, compiled models may not be combined with other models usingmarkovify.combine(...).
If you wish to combine models, do that first and then compile the result.Working with messy textsStarting withv0.7.2,markovify.Textaccepts two additional parameters:well_formedandreject_reg.Settingwell_formed = Falseskips the step in which input sentences are rejected if they contain one of the 'bad characters' (i.e.()[]'")Settingreject_regto a regular expression of your choice allows you change the input-sentence rejection pattern. This only applies ifwell_formedis True, and if the expression is non-empty.Extendingmarkovify.TextThemarkovify.Textclass is highly extensible; most methods can be overridden. For example, the followingPOSifiedTextclass uses NLTK's part-of-speech tagger to generate a Markov model that obeys sentence structure better than a naive model. (It works; however, be warned:pos_tagis very slow.)importmarkovifyimportnltkimportreclassPOSifiedText(markovify.Text):defword_split(self,sentence):words=re.split(self.word_split_pattern,sentence)words=["::".join(tag)fortaginnltk.pos_tag(words)]returnwordsdefword_join(self,words):sentence=" ".join(word.split("::")[0]forwordinwords)returnsentenceOr, you can usespaCywhich isway faster:importmarkovifyimportreimportspacynlp=spacy.load("en_core_web_sm")classPOSifiedText(markovify.Text):defword_split(self,sentence):return["::".join((word.orth_,word.pos_))forwordinnlp(sentence)]defword_join(self,words):sentence=" ".join(word.split("::")[0]forwordinwords)returnsentenceThe most usefulmarkovify.Textmodels you can override are:sentence_splitsentence_joinword_splitword_jointest_sentence_inputtest_sentence_outputFor details on what they do, seethe (annotated) source code.ExportingIt 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 generatedmarkovify.Textmodel, usemy_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(280)>>>'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 thestate_sizemetadata — viamy_text_model.chain.to_json().Generatingmarkovify.Textmodels from very large corporaBy default, themarkovify.Textclass loads, and retains, your textual corpus, so that it can compare generated sentences with the original (and only emit novel sentences). However, with very large corpora, loading the entire text at once (and retaining it) can be memory-intensive. To overcome this, you can(a)tell Markovify not to retain the original:withopen("path/to/my/huge/corpus.txt")asf:text_model=markovify.Text(f,retain_original=False)print(text_model.make_sentence())And(b)read in the corpus line-by-line or file-by-file and combine them into one model at each step:combined_model=Nonefor(dirpath,_,filenames)inos.walk("path/to/my/huge/corpus"):forfilenameinfilenames:withopen(os.path.join(dirpath,filename))asf:model=markovify.Text(f,retain_original=False)ifcombined_model:combined_model=markovify.combine(models=[combined_model,model])else:combined_model=modelprint(combined_model.make_sentence())Markovify In The WildBuzzFeed'sTom Friedman Sentence Generator/@mot_namdeirf./u/user_simulator, a Reddit bot that generates comments based on a user's comment history. [code]SubredditSimulator, whichusesmarkovifyto generate random Reddit submissions and comments based on a subreddit's previous activity. [code]college crapplication, a web-app that generates college application essays. [code]@MarkovPicard, a Twitter bot based onStar Trek: The Next Generationtranscripts. [code]sekrits.herokuapp.com, amarkovify-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, amarkovify-powered Twitter bot attached to a printer. Presented byHelen 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. GeneratesMiraculous Ladybugfanfictions 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]@_murakamibotand@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@NightValeRadiotweets with@BuzzFeedheadlines." [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 bottrainedon Nietzsche, Russell, Kant, Machiavelli, and Plato. [code]funzo-facts, a program that generates never-before-seen trivia based on Jeopardy! questions. [code]Chains Invent Insanity, aCards Against Humanityanswer card generator. [code]@CanDennisDream, a twitter bot that contemplates life by training on existential literature discussions. [code]B-9 Indifference, a program that generates aStar Trek: The Next Generationscript of arbitrary length using Markov chains trained on the show’s episode and movie scripts. [code]adam, polish poetry generator. [code]Stackexchange Simulator, which uses StackExchange's bulk data to generate random questions and answers. [code]@BloggingBot, tweets sentences based on a corpus of 17 years ofblogging.Commencement Speech Generator, generates "graduation speech"-style quotes from a dataset of the "greatest of all time" commencement speeches)@alg_testament, tweets sentences based on The Old Testament and two coding textbooks in Russian. [code]@IRAMockBot, uses Twitter's data on tweets from Russian IRA-associated accounts to produce fake IRA tweets, for educational and study purposes.[code]Personal Whatsapp Chat Analyzer, some basic analytics for WhatsApp chat exports (private & groups), word counting & markov chain phrase generatorDeepfakeBot, a system for converting your friends into Discord bots. [code]python-markov-novel, writes a random novel using markov chains, broken down into chapterspython-ia-markov, trains Markov models on Internet Archive text files@bot_homer, a Twitter bot trained using Homer Simpson's dialogues of 600 chapters. [code].git-commit-gen, generates git commit messages by using markovify to build a model of a repo's git logfakesocial, a fake social network using generated content. [code]Slovodel Bot, a Telegram bot that generates non-existent Russian words using corpus made by algorithmically dividing existent words into syllables.Deuterium, a Discord bot that generates messages on its own, after analyzing yours, and learning constantly. There's also a global model shared with all other servers.Markovify Piano, generates coherent and plausible music generation.Have other examples? Pull requests welcome.ThanksMany thanks to the following GitHub users for contributing code and/or ideas:@orf@deimos@cjmochrie@Jaza@fitnr@andela-mfalade@ntratcliff@schollz@aalireza@bfontaine@tmsherman@wodim@eh11fx@ammgws@OtakuMegane@tsunaminoai@MatthewScholefield@danmayer@kade-robertson@erikerlandson@briennakh@berfr@Freestackmejai@rokala@eumiro@monosansInitially developed atBuzzFeed.