r/dailyprogrammer • u/jnazario 2 0 • Jun 08 '16
[2016-06-08] Challenge #270 [Intermediate] Generating Text with Markov Processes
Description
Text generation algorithms exist in a wide variety of formats, including "Mad Libs" and Markov processes. A Markov chain algorithm generates text by creating a statistical model of potential textual suffixes for a given prefix. That's a fancy way of saying "it basically determines the next most probable word given the training set." Markov chain programs typically do this by breaking the input text into a series of words, then by sliding along them in some fixed sized window, storing the first N-1 words as a prefix and then the Nth word as a member of a set to choose from randomly for the suffix. Then, given a prefix, pick randomly from the suffixes to make the next piece of the chain.
Take this example text:
Now is not the time for desert, now is the time for dinner For a set of triples, yielding a bi-gram (2 word) prefix, we will generate the following prefixes and suffix:
Prefixes Suffixes
-------- --------
Now, is not
is, not the
not, the time
the, time for
time, for desert
for, desert now
desert, now is
now, is not, the
is, the time
the, time for
time, for desert, dinnerYou'll see a couple of the prefixes have TWO suffixes, this is because they repeat but one with a different suffix and one with the same suffix. Repeating this over piles and piles of text will start to enable you to build statistically real but logically meaningless sentences. Take this example output from my program after running it over Star Trek plot summaries:
"attack." In fact, Yeoman Tamura's tricorder shows that Kirk has been killed after
beaming down to the bridge, Kirk reminisces about having time to beam down. Kirk wants
Spock to grab hold of him in a fist fight with Kirk and Spock try to escape, the collars
are activated, subjecting them to an entrance, which then opens. Scotty saves the day by
pretending to help Spock, and Mullhall voluntarily agree, and the others transported to
the one which is not at all obvious what to make diplomatic advances. Meanwhile Kirk is
able to get inside. McCoy and nerve pinches Chief atChallenge
Your challenge today is to implement a Markov generator supporting a bi-gram prefix. It should be capable of ingesting a body of text for training and output a body of text generated from that.
Notes
Markov Chain Algorithm from rose-hulman.edu
If you want to reproduce my Star Trek fun, I extracted the summaries from Eric Wasserman's site and made them into a flat text file.
9
u/Godspiral 3 3 Jun 08 '16
text file might benefit from a .txt extention (not previewable as link)
5
u/hutsboR 3 0 Jun 08 '16 edited Jun 09 '16
Elixir:
Usage:
3
u/MRSantos Jun 08 '16 edited Jul 24 '18
Python 2.7. Generates a never-ending stream of star-trek! The number of words in the prefix is passed as an argument. It's cool to compare the results.
For prefixes that are 10 words long, I got pretty readable results:
Here is some Snoop Dog lyrics for 5 word prefixes (i manually added the \n's since the implementation gets rid of them):
3
u/wizao 1 0 Jun 09 '16 edited Jun 10 '16
Haskell:
Some fun with monad transformers:
3
u/MichaelPenn Jun 09 '16
Python 2.5.1
+/u/CompileBot Python
2
u/casualfrog Jun 08 '16
JavaScript
Somewhat dirty, strips all special characters.
NONWORDin the algorithm linked above is simulated withundefinedand a special starting entry.Output:
2
u/Godspiral 3 3 Jun 08 '16 edited Jun 08 '16
in J,
slow :( - randomly takes any word that follows 2 words in the training text (no "multiplicity" weight). Words follow J grammar.
using space as the word boundary,
2
u/Rzah Jun 08 '16
Another go, this time actually chaining the source text.
NARRATIVE GENERATED:
A unite a stage a coup a revolution a bring a genocide a new chemical and probably performing vivisections and such to ascertain the underlying structure of the meeting's regulars died last night. A king's ransom by your Side Fairy Queen. Thanks to Elian's thoughtfulness, one was not following it entirely. "I am wrestling with God," he said with a rope tied around his ankle so that the original man, the black suit he's wearing to reveal a perfect cross section of the night and day. We hunt the ten thousand things. This is how the scene develops between Corey and her. It was simply a large amount of smaller fish Well, it's all just speculation. The agents noticed some very loud low frequency percussive sounds coming from my set. My god, what kind of psychological mirroring was exploited in the fall, he picked apples from it. Kingdoms rise and fall, men grow and die as humans, and not human, who had made the other side of the abyss and go to her bellybutton, which was mainly a woman standing in my dreams of destruction.
Of destruction. Hello, friends. Thank you for 6 months. I think she sleeps there. I heard her making strange singing sounds from within, frightening sounds. She keeps the portal closed at the same joke I make to myself every time. When I was giggling, just laughing and laughing. The mouth was biting me. I informed him that I would shoot him through the metal.
The metal. There was also a feeling that there is more. There is the smell and make the people were moving in a couple hours. A shot rings out, the first thought when waking up after a week long binge, lying in my little bed. I was a nice one. We took her up and look at Elizabeth Bathory as an tolerable hardship.
code follows:
2
u/jnd-au 0 1 Jun 09 '16
Scala. Provides a
sentencesstream generator for convenience. ‘Multiplicity’, capitalisation and sentence punctuation are preserved for grammatical purposes, but quote marks, parentheses and HTML tags are ignored. Usage:sentences(analyse(text, chainLength)) take numSentencesCode:
Demo with chainLength=2 and numSentences=10, trained on text=“Star Trek TOS Plot Summaries from Eric W Weisstein.txt”:
2
u/porphyro Jun 09 '16
Mathematica
Output for first chapter of Moby Dick as input:
"Call me Ishmael. Some years ago--never mind how long precisely--having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the Saco. What is the battery, where that noble mole is washed by waves, and cooled by breezes, which a few hours previous were out of the needles of the compasses of all earthly ills, and that on no account can a monied man enter heaven. Ah! how cheerfully we consign ourselves to perdition! Finally, I always go to sea as a simple"
2
u/Oczwap Jun 10 '16
Julia
Takes the name of a text file as arg1, and the number of words after which it should try to end the text as as arg2.
2
u/nullmove 1 0 Jun 11 '16
Not surprised or even sad to see no Perl here. But Perl 6, now that's a different story. I have only been at it for a few days, but I am already completely head over heels, and one would really be unwise to dismiss it on grounds of its historical linkage with the predecessor.
(One caveat: it's painfully slow now. But it will be faster...someday. And then it will fix the world)
1
u/Daanvdk 1 0 Jun 08 '16 edited Jun 08 '16
Java
The files I used are the plots of all 7 Harry Potter books copied from Wikipedia. Made my limit optional so I've gotten some really long stories, including a 86 pages long story using your Star Trek textfile.
Example output (one of the shorter ones):
1
u/weekendblues Jun 08 '16 edited Jun 08 '16
Java 8
Sample output (input taken from here):
(Edit 17:15:11 GMT-0400 (EDT) -- adjusted the format of the output in this post).
1
u/Blackshell 2 0 Jun 08 '16
Python 3, quick and dirty. It takes an argument of a training text file, and then uses the remaining command line arguments to start the chain (needs at least two.)
I also have some other files that make for amusing training: the Star Wars original trilogy, and King Lear.
Like this:
1
u/YOLO_Ma Jun 08 '16
In Clojure
I downloaded a text file of Alice's Adventures in Wonderland from Project Gutenberg Using a 3-word markov chain:
Sample output:
1
u/lt_algorithm_gt Jun 08 '16 edited Jun 10 '16
C++, generic to any type (not just strings) and any n-gram length (not just bigrams).
1
u/Scroph 0 0 Jun 09 '16
Ugly C++ solution. Not sure if it even does what it's supposed to, but I explained its behavior in the comments :
Using the flat-text linked file as input, it produces a seemingly infinite output from which I selected the following sample :
1
u/ShaharNJIT 0 1 Jun 09 '16
JavaScript Incomplete but I'm not going to bother too much with this. I did it a bit differently; I included punctuation/etc. marks as words and paused at end of sentences (dots/question marks/exclamation, doesn't work well with titles like 'Mr.' or 'Dr.') because otherwise it gets ridiculous. Fiddle: https://jsfiddle.net/qo3jw67d/
1
u/[deleted] Jun 09 '16
Python 3. I wrote a much better Markov chain generator a while back, but couldn't find it on my computer. This one is far from perfect, but works fine with a correctly formatted text.
And a sample result:
1
u/thorwing Jun 09 '16 edited Jun 09 '16
Java
I remember hearing about markov chains a year ago, I was sneaking into a university class and just stayed their the whole class. Fun to implement a text generator based on it. edit: made it limitable to a certain size if needed, so I can create an output for the starwars.
Output
It's fun to see sentences made from large inputs
1
u/tajjet Jun 09 '16
I'm so lost on this one. Here's what I got in a couple of hours (Python3)
1
u/rakkar16 Jun 09 '16
Python 3
This one expects the input text and the maximum length of the output text (in words) as command line arguments. Also, like the algorithm in the link, this one always gives output that starts with the same words as the original input, though it would be fairly trivial to modify it to start with random bigram from the original text.
1
u/niandra3 Jun 09 '16 edited Jun 09 '16
Python 3. Edit: tweaked it so the first word always chooses randomly one of the capitalized words in the text. And at the end choose a word that ends with a period:
Used 'The Works of Poe vol. 2' to generate 500 words:
The little river which turned all at once, to the foot of the heavens, I had not lived before--that the soul when overcharged with awe. I knew too well the character of the evening, to drink deeply, now shuffled, dealt, or played, with a gasp and a still more imperceptible, this cloud assumes shape, as did the first simpleton; but then a brief moment I perceived my own seat upon the memory; a countenance not easily to be accounted for, and my task was drawing to a seat on one of the current which here sets from the first, we should not have taken it from his grand vizier, to make an offer to the terms of the Medoc." I broke my way through the mind of the water, with the rules is very easy. You may use this expression, because the language of the idiosyncrasy of its fellows that lay upon it. But I must scream or die! and now--again!--hark! louder! louder! "Villains!" I shrieked, "dissemble no more! I admit the identity of name, and doubly disgusted with the fine long needles you have no right to prevent you from copying, distributing, performing, displaying or creating derivative works based on the very purity of the wild audacity of my soul, I once again struggled to perfect--to regain it. Long suffering had nearly reached the extremity of the unusual diagnosis. Hitherto she had endeavored to shriek; and my eyes and the horror of thought, I shook--shook as the motion of this agreement before downloading, copying, displaying, performing, copying or distributing Project Gutenberg-tm electronic work within 90 days of warmth, men have seen me. You should have protected him from a series of sweeps, it turned off at right angles to these agonies foredoomed! There arrived an epoch--as often before there had arrived--in which I speak is, in the regular way, or (what is more than I have just spoken of the schools, so far as the reason that it was a point of correspondence. But, then, the radicalness of the temple, made up your mind that she issued thence at all conversant with authorship may satisfy himself at full-length upon an ottoman. "I see," said I, "the particulars of the fourth year of our search that we could not appreciate distinctly--it was obvious, had taken the passage of a vast number had changed, in a smile of peculiar meaning, the teeth of the Cock-neighs (so the man-animals were called; I presume that I remained standing on the part of beings superior, yet akin to humanity--then the sentiment of spiritual lips upon my head. Oh, you would explain yourself, Mr. Vankirk. V. I am almost ashamed to own--that the terror and its beauty. A whirlwind had apparently collected its force in our company. I must have been wiser, it would have amused me.
1
u/[deleted] Jun 09 '16
Golang
This solution is pretty messy. For each word, it stores the multiplicity of each word that comes after it in a sentence. Then it builds a table to select weighed random words from the chain.
The algorithm is O(N*log(M)) where N is the length of the generated sequence and M is the number of possible selections.
1
u/mbdomecq Jun 09 '16 edited Jun 09 '16
Sample output (minor alterations made for readability):
arrive, Mudd obtains a communicator and says "Kirk to Enterprise," a sliding rack of glasses in what they think to be driven out from her as to measure Kirk's distance from the landing party. Upon thinking about prior to encountering Finigan, Spock realizes that a creature who derives nourishment from the door by pretending to have written herself) and performs an exotic dance (which Spock find similar to Earth, but older, and also reveals that he plans to attend the wedding personally. Meanwhile, Spock has already earned her planet's survival. He also complains and hurls things about the idea of leaving a criminal organization in charge, and also that its crew of a Klingon agent and to salmon on Earth who must return to its. When Kirk questions Flavius to find how he will destruct the Enterprise under Romulan command. The Romulan vessel then ejects debris, inside of which arrives unnoticed a few seconds of real time. Communications with the Federation council. As the storm draws closer, Mira has had a pet sela, a sort of beam from the Earth whose complex "fields" were the only ones on the computer attempting to cover their ears. After reviewing the tape, a high voltage transformer. Kirk then uses the stimulant formazine on Hanar to irritate him (telling him it is learned that although the Gorn ship, since it turns out that this is considered sufficient proof, and Salish is force to jealously gives up his views on command by assassinating Christopher Pike and humankind's unshakable hatred of the supermen, and at one time to develop the atom bomb and conquer the world. On his way to return power and destroys the computer to determine that he therefore cannot interfere with the authorization of Starfleet (who have beamed aboard and faints. Back on the planet surface, he is a classic battle maneuver. The two Kirks then have it out, and Spock as class D- on the transporter operator by Dr. Sanchez reveals that Spock should be needed. As the Enterprise crew members and then subjects Chekov to the slaves' leader Septimus, a former starship doctor who has Scotty beam down for their mental powers, since the only information Uhura can provide the virus. However, Hodin tells Kirk his heir apparent. He then invites Kirk and historian Marla McGivers beam aboard the Enterprise, Hanson is superfluous as navigator in place of Ensign Chekov), the Enterprise immediately. Luckily, Scott is able to escape. The landing party learns that Kirk's obsession is fueled by the cat. Kirk overpowers the guards and run away to scheme with the Trogglytes be supplied with xenite in hand. In Flint's home, McCoy is ready with a knife, then attempts to seduce Kelinda by kissing her, he also sends up hundreds of plants to the xenite miners. Kirk and held him responsible for Finney's lack of complacency and obvious hatred of captivity, and this time has expired, the Tholian fires and damages the Enterprise's engines and switches all power comes back on. Astrobiologist Dr. Anne Mullhall for the entire crew of the past. The Prosecutor has been locked for years. Kirk questions two men into a cell with Spock in private. Spock, who he is leaving, however, McCoy realizes that he wants to kill the Enterprise's crew, phasers and tricorders failed to beam Plasus down as well as dangerous, since neither the outer planet Zeon nor the inner planet Elaas. Here it examines Kirk's medical history, attacking Nurse Chapel "hit me" when he spots the gas cloud, but not kill. Spock orders Boma back to Federation territory. While accompanying the Romulan and scores a minor cut their Philosopher-King Parman has sustained and which is broadcast ship-wide (in which Spock joins in), and Irini distracts Chekov with love and finds that Spock's blood is a negative energy barrier at the beginning. Near the edge of the vicinity, stranding Kirk and Mara use intra-ship beaming to pass through the rock into which Pike was spirited away, but Kirk pooh-poohs his objections. As the landing party, and promptly dies without a readily apparent cause. A strange voice coming from Jackson's mouth then tells Kirk she wants to use himself as a normal part of the Klingon using photon torpedoes on its head and fins on its next pass. Kirk is furious that he is the "ruler" of the minds of Filisa (his wife) and Hanoc (a member of a child. After escaping and hiding in what appears to consult with their help. Khan cuts off life support room, but is able
Source code (C++):
1
u/vishal_mum Jun 10 '16
My Python solution for the example input
1
u/The_Jare Jun 10 '16
Scala
1
u/LiveOnTheSun Jun 10 '16
C# - First time doing an intermediate challenge. It could definitely do with some refactoring as it feels very clunky at the moment. It's 1 am right now and I'm super tired so this will have to do. At least it support different numbers of prefixes and the ability to set a word limit.
Really fun challenge!
Sample output:
McCoy treats Eleen's arm, and also pretends to be inoperable and the Enterprise warps forward in time and the Enterprise bogus instructions using tapes he has made of Kirk's romancing of Deela and attacks him with a knife (fortunately not fatally).
To distract the ambushers, Kirk throws a rock, but is discovered when McCoy gets into trouble. McCoy starts to warn the populace of an ancient culture. Using their communicators, Kirk and a bearded man who had been commanded by Pike and was attempting to cover their ears.
1
u/voice-of-hermes Jun 11 '16
Arbitrary prefix length; handles punctuation (although abbreviations mess it up a bit). Here's a sample (100-word or so) output from the Star Trek fun with a prefix length of 2:
Run like:
Here's the program:
1
u/kittensupernova Jun 14 '16 edited Jun 14 '16
In Go, not the most efficient, but works.
Output when given Edgar Alan Poe's "Purloined Letter": At Paris,just after dark one gusty evening in the game of 'even and odd' attracted universal admiration. This game is simple, and yet baffles us altogether."
1
u/lumos510 Jun 14 '16
Java code. Can't figure out what is wrong. Get a Null Pointer exception when doing Map.get() at line 57. Why is that so?
1
u/taterNuts Jun 16 '16
JavaScript:
Supports variable Order-n values and minimum output length.
Repo with tests located here.
Main code file:
1
u/KingRodian Jun 23 '16 edited Jun 23 '16
C++
Probably very wonky and full of stupid stuff, but I'm too tired to make it better now. Maybe tomorrow.
Should make it have newlines in it so it is actually readable. Oh, and I need to put a limit to the output, because it can become very very long..
Code:
1
u/bitx0r Jun 25 '16 edited Jun 25 '16
AutoHotkey
1
u/mesmoria Jun 26 '16
OCAML
This is the first OCAML program I have ever written, so you can expect something special.
1
u/[deleted] Jul 24 '16
Rust:
Sample:
1
u/BilbroTBaggins Sep 01 '16
A bit late to the party but Python 3
1
u/13467 1 1 Jun 08 '16
Python 3. Prints infinitely many fake paragraphs. Seems to be quite fast.
0
u/[deleted] Jun 09 '16
[deleted] — view deleted comment