Added random word generator

This commit is contained in:
2024-05-07 18:25:22 +01:00
parent c46405efce
commit 599b2c8365
4 changed files with 269 additions and 0 deletions

165
random_word_generator/.gitignore vendored Normal file
View File

@@ -0,0 +1,165 @@
mhyph.txt
syllables.json
venv/
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

View File

@@ -0,0 +1,21 @@
Random Word Generator
=====================
This application makes random words. It's based on syllabels of English words.
I use the mhyph.txt file from Project Gutenberg, so thanks to them for that.
The file can be found here: https://www.gutenberg.org/files/3204/files/mhyph.txt
Usage
-----
You'll need to obtain the mhyph file, stick it in the same folder this file is
in then run ``process_mhyph.py`` file - it'll spit this horrid JSON thingy
which makes the random word generation a bit easier.
Comments
--------
As the title suggests, this is a pretty crap way of doing things I'm pretty sure
but hey, it works, and the words that come out of it are _okay_. Don't look to
this for any inspiration of how to code anything.

View File

@@ -0,0 +1,62 @@
from collections import defaultdict
import json
MHYPH_FILENAME = 'mhyph.txt'
OUTPUT_FILENAME = 'syllables.json'
def def_value():
# MYPH has a 19 syllable long word
return [0] * 19
if __name__ == '__main__':
sd = defaultdict(def_value)
with open(MHYPH_FILENAME, 'rb') as f:
for line in f:
syllables = line.rstrip().split(b'\xa5')
for i, s in enumerate(syllables):
s = s.lower()
# Not sure this is the best way to do this
# But I think it'll work
skip = False
for char in s:
if char < 97 or char > 122:
skip = True
if skip:
continue
sd[s.decode('utf-8')][i] += 1
dictionary = {}
dictionary['syllables and their frequencies per position'] = sd
# Unsure qutie the best term to use here... but these are all the syllables
# stored according to the position they appear in the word
# also stored for each time they appear there - useful (hopefully) for
# making some vaguely real sounding words because it'll kind of represent
# where these syllables are used in real words. Or it might not!
sbp = [ [] ] * 19
for i, s in enumerate(sd):
for j, count in enumerate(sd[s]):
# I have _no_ idea why this needs to be done this way
vector = [s]*count
if i == 0:
sbp[j] = vector
else:
sbp[j].extend(vector)
dictionary['positions and their syllables'] = sbp
# I think I'll probably some "meta" values like totals
# and totals per position or some stuff like that
meta = {}
totals = [0] * 19
for syl in sd:
for i, num in enumerate(sd[syl]):
totals[i] += num
meta['syllable totals'] = totals
meta['total syllables'] = sum(totals)
dictionary['__meta__'] = meta
print(dictionary['__meta__']['syllable totals'])
with open(OUTPUT_FILENAME, 'w') as f:
json.dump(dictionary, f, indent=4)

View File

@@ -0,0 +1,21 @@
from process_mhyph import OUTPUT_FILENAME
import json
import random
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Random Word Generator')
parser.add_argument('-n', '--num', type=int, help='Number of words', default=1)
parser.add_argument('-l', '--length', type=int, help='Length of word(s) to create', default=4)
results = parser.parse_args()
d = {}
with open(OUTPUT_FILENAME, 'r') as f:
d = json.load(f)
for num in range(results.num):
random_word = ''
for i in range(results.length):
random_word += random.choice(d['positions and their syllables'][i])
print(random_word)