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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
|
#!/usr/bin/env python
import sys
from os.path import abspath, exists
from optparse import OptionParser
#!/usr/bin/python
# stripped down by Senthil Palanisami (Sen) [spenthil@gmail.com] to
# work on Google App Engine and exist as a single file
# use as described in http://code.google.com/p/lorem-ipsum-generator/wiki/ApiOverview
# pulled from trunk http://code.google.com/p/lorem-ipsum-generator/ on Monday April 2, 2012
# Copyright (c) James Hales and individual contributors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. The name of contributors may not be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import math
import random
import re
# Delimiters that mark ends of sentences
_DELIMITERS_SENTENCES = ['.', '?', '!']
# Delimiters which do not form parts of words (i.e. "hello," is the word
# "hello" with a comma next to it)
_DELIMITERS_WORDS = [','] + _DELIMITERS_SENTENCES
_NEWLINE = "\n"
_DEFAULT_SAMPLE = """Lorem ipsum dolor sit amet, consectetuer adipiscing elit aenean commodo ligula eget dolor. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
Maecenas tempus tellus eget condimentum rhoncus sem quam semper libero sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel luctus pulvinar hendrerit id lorem. Maecenas nec odio et ante tincidunt tempus.
Nam pretium turpis et arcu duis arcu tortor suscipit eget imperdiet nec imperdiet iaculis ipsum. Integer ante arcu accumsan a consectetuer eget posuere ut mauris.
Curabitur ligula sapien tincidunt non euismod vitae, posuere imperdiet leo. Praesent congue erat at massa sed cursus turpis vitae tortor. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae.
Aenean posuere tortor sed cursus feugiat nunc augue blandit nunc eu sollicitudin urna dolor sagittis lacus. Donec elit libero, sodales nec volutpat a suscipit non turpis.
In dui magna, posuere eget vestibulum et tempor auctor justo. In ac felis quis tortor malesuada pretium proin sapien ipsum porta a auctor quis euismod ut mi. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
Curabitur at lacus ac velit ornare lobortis. Curabitur a felis in nunc fringilla tristique. Pellentesque libero tortor tincidunt et, tincidunt eget semper nec quam.
Maecenas ullamcorper dui et placerat feugiat eros pede varius nisi condimentum viverra felis nunc et lorem. Sed magna purus fermentum eu tincidunt eu varius ut felis.
Fusce convallis metus id felis luctus adipiscing. Pellentesque egestas neque sit amet convallis pulvinar justo nulla eleifend augue ac auctor orci leo non est. Etiam ut purus mattis mauris sodales aliquam.
Sed augue ipsum, egestas nec vestibulum et malesuada adipiscing dui. Vestibulum facilisis purus nec pulvinar iaculis ligula mi congue nunc vitae euismod ligula urna in dolor. Vestibulum rutrum mi nec elementum vehicula, eros quam gravida nisl id fringilla neque ante vel mi.
Mauris turpis nunc blandit et volutpat molestie, porta ut ligula. Fusce pharetra convallis urna donec mi odio faucibus at scelerisque quis convallis in nisi.
Ut id nisl quis enim dignissim sagittis. Etiam sollicitudin ipsum eu pulvinar rutrum tellus ipsum laoreet sapien, quis venenatis ante odio sit amet eros.
Pellentesque commodo eros a enim vestibulum turpis sem aliquet eget lobortis pellentesque rutrum eu nisl. Sed mollis eros et ultrices tempus mauris ipsum aliquam libero non adipiscing dolor urna a orci.
Pellentesque dapibus hendrerit tortor donec vitae orci sed dolor rutrum auctor. Suspendisse nisl elit rhoncus eget elementum ac condimentum eget diam.
Proin viverra, ligula sit amet ultrices semper ligula arcu tristique sapien a accumsan nisi mauris ac eros. Suspendisse faucibus nunc et pellentesque egestas lacus ante convallis tellus vitae iaculis lacus elit id tortor.
"""
_DEFAULT_DICT = """a
ac
accumsan
ad
adipiscing
aenean
aliquam
aliquet
amet
ante
aptent
arcu
at
auctor
augue
bibendum
blandit
class
commodo
condimentum
congue
consectetuer
consequat
conubia
convallis
cras
cubilia
cum
curabitur
curae
cursus
dapibus
diam
dictum
dictumst
dignissim
dis
dolor
donec
dui
duis
egestas
eget
eleifend
elementum
elit
eni
enim
erat
eros
est
et
etiam
eu
euismod
facilisi
facilisis
fames
faucibus
felis
fermentum
feugiat
fringilla
fusce
gravida
habitant
habitasse
hac
hendrerit
hymenaeos
iaculis
id
imperdiet
in
inceptos
integer
interdum
ipsum
justo
lacinia
lacus
laoreet
lectus
leo
libero
ligula
litora
lobortis
lorem
luctus
maecenas
magna
magnis
malesuada
massa
mattis
mauris
metus
mi
molestie
mollis
montes
morbi
mus
nam
nascetur
natoque
nec
neque
netus
nibh
nisi
nisl
non
nonummy
nostra
nulla
nullam
nunc
odio
orci
ornare
parturient
pede
pellentesque
penatibus
per
pharetra
phasellus
placerat
platea
porta
porttitor
posuere
potenti
praesent
pretium
primis
proin
pulvinar
purus
quam
quis
quisque
rhoncus
ridiculus
risus
rutrum
sagittis
sapien
scelerisque
sed
sem
semper
senectus
sit
sociis
sociosqu
sodales
sollicitudin
suscipit
suspendisse
taciti
tellus
tempor
tempus
tincidunt
torquent
tortor
tristique
turpis
ullamcorper
ultrices
ultricies
urna
ut
varius
ve
vehicula
vel
velit
venenatis
vestibulum
vitae
vivamus
viverra
volutpat
vulputate""".split("\n")
def _split_paragraphs(text):
"""
Splits a piece of text into paragraphs, separated by empty lines.
"""
lines = text.splitlines()
paragraphs = [[]]
for line in lines:
if len(line.strip()) > 0:
paragraphs[-1] += [line]
elif len(paragraphs[-1]) > 0:
paragraphs.append([])
paragraphs = map(' '.join, paragraphs)
paragraphs = map(str.strip, paragraphs)
paragraphs = filter(lambda s : s != '', paragraphs)
return paragraphs
def _split_sentences(text):
"""
Splits a piece of text into sentences, separated by periods, question
marks and exclamation marks.
"""
sentence_split = ''
for delimiter in _DELIMITERS_SENTENCES:
sentence_split += '\\' + delimiter
sentence_split = '[' + sentence_split + ']'
sentences = re.split(sentence_split, text.strip())
sentences = map(str.strip, sentences)
sentences = filter(lambda s : s != '', sentences)
return sentences
def _split_words(text):
"""
Splits a piece of text into words, separated by whitespace.
"""
return text.split()
def _mean(values):
return sum(values) / float(max(len(values), 1))
def _variance(values):
squared = list(map(lambda x : x**2, values))
return _mean(squared) - _mean(values)**2
def _sigma(values):
return math.sqrt(_variance(values))
def _choose_closest(values, target):
"""
Find the number in the list of values that is closest to the target.
Prefer the first in the list.
"""
closest = list(values)[0]
for value in values:
if abs(target - value) < abs(target - closest):
closest = value
return closest
def _get_word_info(word):
longest = (word, "")
for delimiter in _DELIMITERS_WORDS:
if len(delimiter) > len(longest[1]) and word.endswith(delimiter):
word = word.rpartition(delimiter)
longest = (word[0], word[1])
return (len(longest[0]), longest[1])
class InvalidDictionaryError(Exception):
def __str__(self):
return ('The dictionary must be a list of one or more words.')
class InvalidSampleError(Exception):
def __str__(self):
return ('The sample text must contain one or more empty-line '
'delimited paragraphs, and each paragraph must contain one or '
'more period, question mark, or exclamation mark delimited '
'sentences.')
class Generator(object):
"""
Generates random strings of "lorem ipsum" text.
Markov chains are used to generate the random text based on the analysis
of a sample text. In the analysis, only paragraph, sentence and word
lengths, and some basic punctuation matter -- the actual words are
ignored. A provided list of words is then used to generate the random text,
so that it will have a similar distribution of paragraph, sentence and word
lengths.
"""
# Words that can be used in the generated output
# Maps a word-length to a list of words of that length
__words = {}
# Chains of three words that appear in the sample text
# Maps a pair of word-lengths to a third word-length and an optional
# piece of trailing punctuation (for example, a period, comma, etc.)
__chains = {}
# Pairs of word-lengths that can appear at the beginning of sentences
__starts = []
# Sample that the generated text is based on
__sample = ""
# Statistics for sentence and paragraph generation
__sentence_mean = 0
__sentence_sigma = 0
__paragraph_mean = 0
__paragraph_sigma = 0
# Last calculated statistics, in case they are overwritten by user
__generated_sentence_mean = 0
__generated_sentence_sigma = 0
__generated_paragraph_mean = 0
__generated_paragraph_sigma = 0
def __init__(self, sample=_DEFAULT_SAMPLE, dictionary=_DEFAULT_DICT):
"""
Initialises a generator that will use the provided sample text and
dictionary to produce sentences.
"""
self.sample = sample
self.dictionary = dictionary
def __set_sentence_mean(self, mean):
if mean < 0:
raise ValueError('Mean sentence length must be non-negative.')
self.__sentence_mean = mean
def __set_sentence_sigma(self, sigma):
if sigma < 0:
raise ValueError('Standard deviation of sentence length must be '
'non-negative.')
self.__sentence_sigma = sigma
def __set_paragraph_mean(self, mean):
if mean < 0:
raise ValueError('Mean paragraph length must be non-negative.')
self.__paragraph_mean = mean
def __set_paragraph_sigma(self, sigma):
if sigma < 0:
raise ValueError('Standard deviation of paragraph length must be '
'non-negative.')
self.__paragraph_sigma = sigma
def __get_sentence_mean(self):
"""
A non-negative value determining the mean sentence length (in words)
of generated sentences. Is changed to match the sample text when the
sample text is updated.
"""
return self.__sentence_mean
def __get_sentence_sigma(self):
"""
A non-negative value determining the standard deviation of sentence
lengths (in words) of generated sentences. Is changed to match the
sample text when the sample text is updated.
"""
return self.__sentence_sigma
def __get_paragraph_mean(self):
"""
A non-negative value determining the mean paragraph length (in
sentences) of generated sentences. Is changed to match the sample text
when the sample text is updated.
"""
return self.__paragraph_mean
def __get_paragraph_sigma(self):
"""
A non-negative value determining the standard deviation of paragraph
lengths (in sentences) of generated sentences. Is changed to match the
sample text when the sample text is updated.
"""
return self.__paragraph_sigma
sentence_mean = property(__get_sentence_mean, __set_sentence_mean)
sentence_sigma = property(__get_sentence_sigma, __set_sentence_sigma)
paragraph_mean = property(__get_paragraph_mean, __set_paragraph_mean)
paragraph_sigma = property(__get_paragraph_sigma, __set_paragraph_sigma)
def __generate_chains(self, sample):
"""
Generates the __chains and __starts values required for sentence generation.
"""
words = _split_words(sample)
if len(words) <= 0:
raise InvalidSampleError
word_info = map(_get_word_info, words)
previous = (0, 0)
chains = {}
starts = [previous]
for pair in word_info:
if pair[0] == 0:
continue
chains.setdefault(previous, []).append(pair)
if pair[1] in _DELIMITERS_SENTENCES:
starts.append(previous)
previous = (previous[1], pair[0])
if len(chains) > 0:
self.__chains = chains
self.__starts = starts
else:
raise InvalidSampleError
def __generate_statistics(self, sample):
"""
Calculates the mean and standard deviation of sentence and paragraph lengths.
"""
self.__generate_sentence_statistics(sample)
self.__generate_paragraph_statistics(sample)
self.reset_statistics()
def __generate_sentence_statistics(self, sample):
"""
Calculates the mean and standard deviation of the lengths of sentences
(in words) in a sample text.
"""
sentences = filter(lambda s : len(s.strip()) > 0, _split_sentences(sample))
sentence_lengths = list(map(lambda a: len(list(a)), map(_split_words, sentences)))
self.__generated_sentence_mean = _mean(sentence_lengths)
self.__generated_sentence_sigma = _sigma(sentence_lengths)
def __generate_paragraph_statistics(self, sample):
"""
Calculates the mean and standard deviation of the lengths of paragraphs
(in sentences) in a sample text.
"""
paragraphs = filter(lambda s : len(s.strip()) > 0, _split_paragraphs(sample))
paragraph_lengths = list(map(lambda a: len(list(a)), map(_split_sentences, paragraphs)))
self.__generated_paragraph_mean = _mean(paragraph_lengths)
self.__generated_paragraph_sigma = _sigma(paragraph_lengths)
def reset_statistics(self):
"""
Returns the values of sentence_mean, sentence_sigma, paragraph_mean,
and paragraph_sigma to their values as calculated from the sample
text.
"""
self.sentence_mean = self.__generated_sentence_mean
self.sentence_sigma = self.__generated_sentence_sigma
self.paragraph_mean = self.__generated_paragraph_mean
self.paragraph_sigma = self.__generated_paragraph_sigma
def __get_sample(self):
"""
The sample text that generated sentences are based on.
Sentences are generated so that they will have a similar distribution
of word, sentence and paragraph lengths and punctuation.
Sample text should be a string consisting of a number of paragraphs,
each separated by empty lines. Each paragraph should consist of a
number of sentences, separated by periods, exclamation marks and/or
question marks. Sentences consist of words, separated by white space.
"""
return self.__sample
def __set_sample(self, sample):
self.__sample = sample
self.__generate_chains(sample)
self.__generate_statistics(sample)
def __get_dictionary(self):
"""
The list of words that generated sentences are made of.
The dictionary should be a list of one or more words, as strings.
"""
dictionary = []
map(dictionary.extend, self.__words.values())
return dictionary
def __set_dictionary(self, dictionary):
words = {}
for word in dictionary:
try:
word = str(word)
words.setdefault(len(word), set()).add(word)
except TypeError:
continue
if len(words) > 0:
self.__words = words
else:
raise InvalidDictionaryError
sample = property(__get_sample, __set_sample)
dictionary = property(__get_dictionary, __set_dictionary)
def __choose_random_start(self):
starts = set(self.__starts)
chains = set(self.__chains.keys())
valid_starts = list(chains.intersection(starts))
return random.choice(valid_starts)
def generate_sentence(self, start_with_lorem=False):
"""
Generates a single sentence, of random length.
If start_with_lorem=True, then the sentence will begin with the
standard "Lorem ipsum..." first sentence.
"""
if len(self.__chains) == 0 or len(self.__starts) == 0:
raise InvalidSampleError
if len(self.__words) == 0:
raise InvalidDictionaryError
# The length of the sentence is a normally distributed random variable.
sentence_length = random.normalvariate(self.sentence_mean,
self.sentence_sigma)
sentence_length = max(int(round(sentence_length)), 1)
sentence = []
previous = ()
word_delimiter = '' # Defined here in case while loop doesn't run
# Start the sentence with "Lorem ipsum...", if desired
if start_with_lorem:
lorem = "lorem ipsum dolor sit amet, consecteteur adipiscing elit"
lorem = lorem.split()
sentence += lorem[:sentence_length]
last_char = sentence[-1][-1]
if last_char in _DELIMITERS_WORDS:
word_delimiter = last_char
# Generate a sentence from the "chains"
while len(sentence) < sentence_length:
# If the current starting point is invalid, choose another randomly
if (previous not in self.__chains):
previous = self.__choose_random_start()
# Choose the next "chain" to go to. This determines the next word
# length we'll use, and whether there is e.g. a comma at the end of
# the word.
chain = random.choice(self.__chains[previous])
word_length = chain[0]
# If the word delimiter contained in the chain is also a sentence
# delimiter, then we don't include it because we don't want the
# sentence to end prematurely (we want the length to match the
# sentence_length value).
if chain[1] in _DELIMITERS_SENTENCES:
word_delimiter = ''
else:
word_delimiter = chain[1]
# Choose a word randomly that matches (or closely matches) the
# length we're after.
closest_length = _choose_closest(
self.__words.keys(),
word_length)
word = random.choice(list(self.__words[closest_length]))
sentence += [word + word_delimiter]
previous = (previous[1], word_length)
# Finish the sentence off with capitalisation, a period and
# form it into a string
sentence = ' '.join(sentence)
sentence = sentence.capitalize()
sentence = sentence.rstrip(word_delimiter) + '.'
return sentence
def generate_paragraph(self, start_with_lorem=False):
"""
Generates a single lorem ipsum paragraph, of random length.
If start_with_lorem=True, then the paragraph will begin with the
standard "Lorem ipsum..." first sentence.
"""
paragraph = []
# The length of the paragraph is a normally distributed random variable.
paragraph_length = random.normalvariate(self.paragraph_mean,
self.paragraph_sigma)
paragraph_length = max(int(round(paragraph_length)), 1)
# Construct a paragraph from a number of sentences.
while len(paragraph) < paragraph_length:
sentence = self.generate_sentence(
start_with_lorem = (start_with_lorem and len(paragraph) == 0)
)
paragraph += [sentence]
# Form the paragraph into a string.
paragraph = ' '.join(paragraph)
return paragraph
class MarkupGenerator(Generator):
"""
Provides a number of methods for producing "lorem ipsum" text with
varying formats.
"""
def __generate_markup(self, begin, end, between, quantity,
start_with_lorem, function):
"""
Generates multiple pieces of text, with begin before each piece, end
after each piece, and between between each piece. Accepts a function
that returns a string.
"""
text = []
while len(text) < quantity:
part = function(
start_with_lorem = (start_with_lorem and len(text) == 0)
)
part = begin + part + end
text += [part]
text = between.join(text)
return text
def __generate_markup_paragraphs(self, begin_paragraph, end_paragraph,
between_paragraphs, quantity, start_with_lorem=False):
return self.__generate_markup(
begin_paragraph,
end_paragraph,
between_paragraphs,
quantity,
start_with_lorem,
self.generate_paragraph)
def __generate_markup_sentences(self, begin_sentence, end_sentence,
between_sentences, quantity, start_with_lorem=False):
return self.__generate_markup(
begin_sentence,
end_sentence,
between_sentences,
quantity,
start_with_lorem,
self.generate_sentence)
def generate_paragraphs_plain(self, quantity, start_with_lorem=False):
"""Generates a number of paragraphs, separated by empty lines."""
return self.__generate_markup_paragraphs(
begin_paragraph='',
end_paragraph='',
between_paragraphs=_NEWLINE * 2,
quantity=quantity,
start_with_lorem=start_with_lorem
)
def generate_sentences_plain(self, quantity, start_with_lorem=False):
"""Generates a number of sentences."""
return self.__generate_markup_sentences(
begin_sentence='',
end_sentence='',
between_sentences=' ',
quantity=quantity,
start_with_lorem=start_with_lorem
)
def generate_paragraphs_html_p(self, quantity, start_with_lorem=False):
"""
Generates a number of paragraphs, with each paragraph
surrounded by HTML pararaph tags.
"""
return self.__generate_markup_paragraphs(
begin_paragraph='<p>' + _NEWLINE + '\t',
end_paragraph=_NEWLINE + '</p>',
between_paragraphs=_NEWLINE,
quantity=quantity,
start_with_lorem=start_with_lorem
)
def generate_sentences_html_p(self, quantity, start_with_lorem=False):
"""
Generates a number of sentences, with each sentence
surrounded by HTML pararaph tags.
"""
return self.__generate_markup_sentences(
begin_sentence='<p>' + _NEWLINE + '\t',
end_sentence=_NEWLINE + '</p>',
between_sentences=_NEWLINE,
quantity=quantity,
start_with_lorem=start_with_lorem
)
def generate_paragraphs_html_li(self, quantity, start_with_lorem=False):
"""Generates a number of paragraphs, separated by empty lines."""
output = self.__generate_markup_paragraphs(
begin_paragraph='\t<li>\n\t\t',
end_paragraph='\n\t</li>',
between_paragraphs=_NEWLINE,
quantity=quantity,
start_with_lorem=start_with_lorem
)
return ('<ul>' + _NEWLINE + output + _NEWLINE + '</ul>')
def generate_sentences_html_li(self, quantity, start_with_lorem=False):
"""Generates a number of sentences surrounded by HTML 'li' tags."""
output = self.__generate_markup_sentences(
begin_sentence='\t<li>' + _NEWLINE + '\t\t',
end_sentence=_NEWLINE + '\t</li>',
between_sentences=_NEWLINE,
quantity=quantity,
start_with_lorem=start_with_lorem
)
return ('<ul>' + _NEWLINE + output + _NEWLINE + '</ul>')
####################
def load_contents(file):
file = open(abspath(file), 'r')
contents = file.read()
file.close()
return contents
def main():
(options, args) = parse_args()
generator = init_generator(options)
start_cli(options, generator)
def parse_args():
parser = OptionParser()
parser.add_option("-p", "--paragraphs", dest="paragraphs", help="generate NUM paragraphs", metavar="NUM", type="int")
parser.add_option("-s", "--sentences", dest="sentences", help="generate NUM sentences", metavar="NUM", type="int")
parser.add_option("--sample", dest="sample_path", help="use FILE as the sample text", metavar="FILE")
parser.add_option("--dictionary", dest="dictionary_path", help="use FILE as the dictionary text", metavar="FILE")
parser.add_option("--sentence-mean", dest="sentence_mean", help="set the mean sentence length to NUM", metavar="NUM", type="float")
parser.add_option("--paragraph-mean", dest="paragraph_mean", help="set the mean paragraph length to NUM", metavar="NUM", type="float")
parser.add_option("--sentence-sigma", dest="sentence_sigma", help="set the standard deviation sentence length to NUM", metavar="NUM", type="float")
parser.add_option("--paragraph-sigma", dest="paragraph_sigma", help="set the standard deviation paragraph length to NUM", metavar="NUM", type="float")
parser.add_option("-l", "--lorem", dest="lorem", action="store_true", help="start with \"Lorem ipsum dolor...\"")
parser.add_option("-f", "--format", metavar="FORMAT", dest="format", action="store", help="produce format in plain, html-p, or html-li format", choices=("plain", "html-p", "html-li"))
parser.add_option("-g", "--gui", dest="gui", action="store_true", help="force GUI to start")
return parser.parse_args()
def init_generator(options):
generator = MarkupGenerator()
# Set the sample and dictionary texts
if options.sample_path:
try:
generator.sample = load_contents(options.sample_path)
except IOError:
error('Unable to load sample file "%s".\n' % options.sample_path)
except InvalidSampleError:
error('Invalid sample file "%s".\n' % options.sample_path)
if options.dictionary_path:
try:
generator.dictionary = load_contents(options.dictionary_path).split()
except IOError:
error('Unable to load dictionary file "%s".\n' % options.dictionary_path)
except InvalidDictionaryError:
error('Invalid sample file "%s".\n' % options.dictionary_path)
# Set statistics
try:
if options.sentence_mean:
generator.sentence_mean = options.sentence_mean
if options.paragraph_mean:
generator.paragraph_mean = options.paragraph_mean
if options.sentence_sigma:
generator.sentence_sigma = options.sentence_sigma
if options.paragraph_sigma:
generator.paragraph_sigma = options.paragraph_sigma
except ValueError as e:
error("%s\n" % e)
return generator
def error(message):
sys.stderr.write(message)
exit()
def start_cli(options, generator):
output = ""
if options.paragraphs:
if options.format == "html-p":
output = generator.generate_paragraphs_html_p(options.paragraphs, options.lorem)
elif options.format == "html-li":
output = generator.generate_paragraphs_html_li(options.paragraphs, options.lorem)
else:
output = generator.generate_paragraphs_plain(options.paragraphs, options.lorem)
elif options.sentences:
if options.format == "html-p":
output = generator.generate_sentences_html_p(options.sentences, options.lorem)
elif options.format == "html-li":
output = generator.generate_sentences_html_li(options.sentences, options.lorem)
else:
output = generator.generate_sentences_plain(options.sentences, options.lorem)
print(output)
if __name__ == '__main__':
main()
|