Last active
March 4, 2022 05:02
-
-
Save colinjroberts/148b251b130f6954dcb9d01dc1007401 to your computer and use it in GitHub Desktop.
From korean-typing-practice-part1: A Flask app for generating random words in English
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from string import ascii_letters, ascii_lowercase | |
from flask import Flask, request | |
from random import randint | |
app = Flask(__name__) | |
@app.route('/') | |
def hello(): | |
return "Use the route /text with the following arguments: letters to use " | |
"in the words, number of words to generate. " | |
"e.g. localhost:5000/text?letters=abcde&count=5" | |
@app.route('/text', methods=['GET']) | |
def get_text(): | |
MAX_WORD_LENGTH = 6 | |
# Get arguments and return helpful errors if missing | |
args = request.args.to_dict() | |
count_of_words_to_return = int(args.get('count')) | |
letters_provided = args.get('letters') | |
if not (count_of_words_to_return and letters_provided): | |
raise ValueError(f"int count expected, {count_of_words_to_return} was \ | |
provided; string letters expected, \ | |
{letters_provided} was provided") | |
elif int(count_of_words_to_return) <= 0: | |
raise ValueError(f"int count must be greater than 0: \ | |
{count_of_words_to_return} was provided") | |
def handle_input(count_of_words_to_return, letters_provided, max_word_length): | |
# Deduplicate list of letters | |
set_of_letters = deduplicate_letters_EN(letters_provided) | |
# Throw an error if there are no ascii letters in the set | |
if len(set_of_letters) <= 0: | |
raise ValueError(f"string letters expected at least 1 ascii letter, \ | |
{set_of_letters} was provided") | |
# Create and return the number of requested words | |
output = create_many_words_EN(set_of_letters, count_of_words_to_return, max_word_length) | |
return ", ".join(output) | |
def deduplicate_letters(list_of_letters): | |
set_of_letters = set() | |
for char in list_of_letters: | |
if char in ascii_letters: | |
set_of_letters.add(char.lower()) | |
return set_of_letters | |
def create_one_word(list_of_letters, word_length): | |
list_of_letters_for_new_word = [] | |
for i in range(word_length): | |
random_letter = list_of_letters[randint(0, len(list_of_letters)-1)] | |
list_of_letters_for_new_word.append(random_letter) | |
return "".join(list_of_letters_for_new_word) | |
def create_many_words(set_of_letters, number_of_words, max_word_length): | |
output = [] | |
for i in range(number_of_words): | |
random_word_length = randint(1, max_word_length) | |
output.append(create_one_word(list(set_of_letters), random_word_length)) | |
return output |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment