I am making a "wordlist cleaner" module that loads a words.txt
file, and returns a list of cleaned/sorted words.
Full code:
import logging
MIN_WORD_LENGTH = 3
MAX_WORD_LENGTH = 25
class WordlistCleaner:
def _load_words_from_file(self, words_file: str):
"""Loads a list of words from a file"""
words = [line.strip() for line in open(words_file, encoding="utf-8").read().lower().splitlines()]
if len(words) == 0:
logging.warning(f"No words were found in the {words_file} file.\nExiting script...")
quit()
return words
def _remove_invalid_words(self, words: list[str]):
"""Cleans a list of words by removing words that do not adhere to requirements"""
valid_words = []
for word in words:
if len(word) > MAX_WORD_LENGTH or len(word) < MIN_WORD_LENGTH:
logging.warning(f"{word} has been excluded - words MIN_word_LENGTH be between 3 and 25 characters.")
continue
try:
word.encode("ascii")
except UnicodeEncodeError:
logging.warning(f"{word} has been excluded - words must not contain Unicode characters.")
continue
valid_words.append(word)
return valid_words
def _remove_duplicates(self, words: list[str]):
"""Removes duplicates from a list"""
return list(set(words))
def clean_words(self, words_file: str):
"""Takes a filename / filepath as input and returns the cleaned words"""
unsorted_words= self._load_words_from_file(words_file)
valid_words = self._remove_invalid_words(unsorted_words)
if len(unsorted_words) > len(valid_words):
logging.warning(
f"{len(unsorted_words)-len(valid_words)} words have been removed from the list as they were invalid"
)
sorted_words = self._remove_duplicates(valid_words)
if len(valid_words) > len(sorted_words):
logging.warning(f"{len(valid_words)-len(sorted_words)} duplicate words have been found and removed")
with open(words_file, "w", encoding="ascii") as f:
for word in sorted_words:
f.write(word + "\n")
logging.info(f"The {words_file} file has been updated.")
return sorted_words
cleaner = WordlistCleaner()
cleaned_wordlist = cleaner.clean_words("words.txt")
The goal is to just load a wordlist and make sure that every word adheres to requirements. This includes removing duplicates, words with Unicode characters, and words that don't meet character limits.
I was wondering if anyone knew how I could clean up the code a bit, since it feels very messy now. I also have a habit of having this "top down" method execution approach when writing classes. That is, the method at the bottom of the class executes all of the top methods chronologically until it reaches the bottom. Not sure if there's anything wrong with that, but it is definitely a pattern I've noticed in a few of my programs.
Moreover, I'm not sure if it's bad practice to call quit()
if an empty file is provided, or if an exception would be more appropriate.
Thank you in advance for any help/suggestions.