Skip to content

Instantly share code, notes, and snippets.

@robxx
Created April 21, 2024 23:31
Show Gist options
  • Select an option

  • Save robxx/b9832436e64d736f8a67e0c1c0057a3b to your computer and use it in GitHub Desktop.

Select an option

Save robxx/b9832436e64d736f8a67e0c1c0057a3b to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
#
# travesty2.py
# translated by chatgpt 3.5
###########################################################
#
# travesty2.pl
#
# a third version of travesty to try to speed things up
# by Ron Starr
#
#
# Generates a text matching letter frequency of input text.
#
#
# Program does no error checking--you're on your own.
#
#
# Command-line options:
# -g <number> The granularity--the number of letters to use to determine
# the next letter. Defaults to 3.
# -o <number> The number of letters to output. Defaults to 100.
#
#
# Program reads from standard input.
# All output is to standard output.
#
#
# Revision History
# 05/16/00 First version started.
# 05/18/00 ftravesty - attempt to do things w/
# integers
# 05/21/00 Version that constructs the table
#
###########################################################
import sys
import random
import getopt
# Set default values for options
MAXLETTERS = 100
GRAIN = 3
LETTERS_LINE = 70
# Read command line options
opts, args = getopt.getopt(sys.argv[1:], "g:o:")
for opt, arg in opts:
if opt == "-g":
GRAIN = int(arg)
elif opt == "-o":
MAXLETTERS = int(arg)
# Pull in the text, break it into letters, put in letter array
textletters = []
for line in sys.stdin:
text = line.strip() + " "
# Regularize whitespace in order to split text into letters
text = ' '.join(text.split())
textletters.extend(list(text))
# Generate the frequency table
frequency_table = {}
# Calculate outer loop limits
loopmax = len(textletters) - (GRAIN - 1) - 1
# Go through all lists of GRAIN letters in the text
for j in range(loopmax):
key_string = "".join(textletters[j:j + GRAIN])
frequency_table.setdefault(key_string, []).append(textletters[j + GRAIN])
# Generate the travesty
buffer = []
lastletters = textletters[:GRAIN]
for i in range(MAXLETTERS):
# Construct the key string from the last letters
key_string = "".join(lastletters)
if key_string in frequency_table:
possible = frequency_table[key_string]
nextletter = random.choice(possible)
buffer.append(nextletter)
if len(buffer) >= LETTERS_LINE and buffer[-1] == " ":
print(''.join(buffer))
buffer = []
lastletters = lastletters[1:] + [nextletter]
else:
lastletters = textletters[:GRAIN]
if buffer:
print(''.join(buffer))
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment