This class takes a text (preferably long enough) and generates another text that "looks like" the original. It won't mean anything, or just by chance ;-)
For example, taking Hamlet, Act I, the program generates things like :
Hamlet
And vanish'd from our watch;
His further. Fare third nights of the flushing immortal as it draw you into the flushing thy complete steel
'Tis sweet and each new-hatch'd:
A country's father;
To business and is prodigal thee!
Have of crowing more the should I have heaven,
Forward, therefore as ourself in the business it, Horatio
To what is't that your watch, bid this here!
Usage :
generator = TextGenerator(txt)
result = generator.random_text(3000)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | # -*- coding: iso-8859-1 -*-
"""Generate a text with words looking like those in a given text,
based on the frequency of character sequences
"""
import string
import io
import random
class TextGenerator:
def __init__(self,txt,seq_len=5):
"""txt = original text
seq_len = sequence length ; 3 to 6 give the best results"""
# dictionary mapping sequences of seq_len chararcters to the list
# of characters following them in the original text
self.followers = {}
for i in range(len(txt)-2*seq_len):
sequence = txt[i:i+seq_len] # sequence of seq_len characters
next_char = txt[i+seq_len] # the character following this sequence
if sequence in self.followers:
self.followers[sequence].append(next_char)
else:
self.followers[sequence]=[next_char]
# sequences that start with an uppercase letter
starts = [ key for key in self.followers
if key[0] in string.ascii_uppercase ]
if not starts: # just in case...
starts = list(self.followers.keys())
# build a distribution of these sequences with the same frequency
# as in the original text
self.starts = []
for key in starts:
for i in range(len(self.followers[key])):
self.starts.append(key)
def random_text(self,length=5000):
"""length = length of the generated text"""
# pick a start at random and initialize
# generated text with this sequence
sequence = random.choice(self.starts)
gen_text = io.StringIO()
gen_text.write(sequence)
for j in range(length):
# pick a character among those following current sequence
next_char = random.choice(self.followers[sequence])
gen_text.write(next_char)
sequence = sequence[1:]+next_char
return gen_text.getvalue()
if __name__=="__main__":
import re
txt = open('hamlet.txt').read()
txt = re.sub("\n+",'\n',txt)
gen = TextGenerator(txt)
res = gen.random_text(3000)
out = open('result.txt','w')
out.write(res)
out.close()
|
The program can be used just for fun, or to generate random text for application testing. It can also be helpful for uninspired poets and songwriters