Advertisement
Open Source Projects by Phil Schwartz

Building a Python Lorem Ipsum Generator with Custom Word Counts

A small text-generation utility is an excellent Python project because it combines string handling, random selection, command-line design and practical testing. A Lorem Ipsum generator can begin as a few lines of code, then develop into a reusable tool for mock-ups, documentation, database fixtures and interface testing.

The central requirement is simple: accept a requested word count and return readable placeholder text with exactly that many words. A well-designed implementation should also handle invalid input, produce stable output when required, and remain easy to install on Linux, macOS and Windows. For Australian developers, it can support local editorial conventions such as Australian English spelling when generated text is mixed with real copy for Sydney, Melbourne or Brisbane projects.

Choosing a Practical Generator Design

There are two common approaches to placeholder text. The first stores a fixed passage and truncates it to the requested length. This is predictable and gives the familiar “Lorem ipsum dolor sit amet” opening. The second selects words from a vocabulary and builds a new passage, providing more variation for repeated test runs.

A fixed corpus is usually the better starting point. It avoids awkward word combinations, keeps the output deterministic and makes testing straightforward. Store the source text as a Python constant, normalise whitespace, split it into words, and return a slice. The utility can later add a random mode without changing its command-line interface.

Word counting needs a clear definition. For most mock content, punctuation attached to a word should not create an extra item, so amet, counts as one word. A regular expression can extract word-like sequences, although a simple whitespace split is sufficient when the source corpus has already been cleaned.

Writing the Word-Count Engine

The core function should receive an integer and return a string. It should reject zero, negative numbers and values that are not integers. Raising ValueError keeps the function useful in other Python programs, while the command-line layer can convert that exception into a friendly error message.

import re

LOREM = """
Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua Ut enim ad minim veniam
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat Duis aute irure dolor in reprehenderit voluptate velit esse cillum
dolore eu fugiat nulla pariatur Excepteur sint occaecat cupidatat non
proident sunt in culpa qui officia deserunt mollit anim id est laborum
"""

def generate_lorem(word_count: int) -> str:
    if not isinstance(word_count, int) or isinstance(word_count, bool):
        raise ValueError("word count must be an integer")
    if word_count < 1:
        raise ValueError("word count must be greater than zero")

    words = re.findall(r"\b[\w'-]+\b", LOREM)
    selected = [words[index % len(words)] for index in range(word_count)]
    return " ".join(selected) + "."

Using modular indexing means the function can generate 500 words even when the source passage contains fewer words. For a simple filler tool, repeated sequences are acceptable. If natural variation matters, use random.sample when the requested count is smaller than the corpus, or random.choice for each position when repetition is allowed.

Adding a Command-Line Interface

A command-line interface makes the script useful in shell pipelines, build tasks and local development. Python’s argparse module supplies help text, type conversion and validation without requiring an external dependency. A developer in Perth can run the tool while preparing sample data, just as a team in Adelaide can use it during a documentation build.

import argparse

def main() -> None:
    parser = argparse.ArgumentParser(
        description="Generate Lorem Ipsum placeholder text."
    )
    parser.add_argument(
        "words",
        type=int,
        help="number of words to generate"
    )
    args = parser.parse_args()

    try:
        print(generate_lorem(args.words))
    except ValueError as error:
        parser.error(str(error))

if __name__ == "__main__":
    main()

Save the file as lorem.py and run python lorem.py forty only if the interface is later extended to parse written numbers; the current version correctly expects a numeric argument such as python lorem.py 40. The generated text can be redirected into a file with python lorem.py 250 > sample.txt, which is useful for testing forms, page layouts and import routines.

Behaviours Worth Testing

Useful Test Inputs

Improving Output Quality and Reproducibility

A basic word slicer may end with an unnatural fragment or punctuation pattern. A better version can capitalise the first word, add a full stop, and optionally insert commas at controlled intervals. Paragraph support is another useful feature: accept both a total word count and a paragraph size, then split the result into blocks without changing the total.

Random generation requires a decision about reproducibility. Unseeded randomness produces different output on every run, which is useful for visual testing but inconvenient for automated tests. Add an optional --seed argument and pass a local random.Random(seed) instance to the generator. This keeps results repeatable without changing Python’s global random state.

The utility should also use UTF-8 when reading an external corpus. Australian projects often combine placeholder content with names, product labels and copy prepared for local markets. Keeping encoding explicit prevents surprises when files contain accented names or typographic punctuation.

Packaging, Licensing and Distribution

Once the script is useful beyond one workstation, give it a small package layout with a library module, a command-line entry point and tests. A pyproject.toml file allows modern Python packaging tools to install it consistently. Include a README showing commands, supported Python versions and examples of custom word counts.

Files That Keep the Project Clear

Release Checks Before Sharing

Licensing matters when the tool is published as open source. A permissive licence such as MIT is common for small developer utilities, while a project using a third-party corpus must follow that corpus’s terms. Australian copyright law still applies to software and written source material, so a “free online” passage should not automatically be treated as reusable.

Fitting the Utility into Australian Development Workflows

A lightweight generator can support local agencies, software teams and freelance developers producing landing pages for Australian businesses. It can fill a responsive layout for a café in Melbourne, supply fixture records for a Sydney SaaS dashboard, or create long-form content blocks for an e-commerce site serving regional Queensland. These examples are fictional, but they reflect common testing needs across the Australian market.

Use Australian English in documentation where appropriate: “customise”, “licence” as a noun, and “organisation” will feel natural to local users. The tool itself does not need to translate Lorem Ipsum, yet its help text and README should match the conventions expected by Australian teams. It can also be integrated into weekday development routines, where a developer generates sample content locally rather than sending unnecessary test data through a hosted service.

Privacy is another practical consideration. Placeholder generation should happen entirely offline and should never require customer names, addresses or production records. That is useful for organisations reviewing obligations under Australia’s Privacy Act 1988, particularly when developers are preparing fixtures on personal laptops or shared staging systems. A self-contained Python utility keeps test content separate from real personal information while remaining fast enough for everyday use.