I'm trying to improve my dirty data wrangling code into something nice, readable & reliable.
I believe I've done fairly well here, although maybe I should have some docstrings on my functions. Still, I believe it's fairly readable without them.
I'd love some feedback on ways to improve! This script parses raw data from Gray Ward's fantastic public-domain thesaurus into a more readable JSON file.
import sys
import os
import json
# Parses Grady Ward's public-domain thesaurus, available at
# ftp://svr-ftp.eng.cam.ac.uk/pub/comp.speech/dictionaries/moby/
def main():
database = {}
if len(sys.argv) < 3:
print("Usage: make_database <input filename> <ouput filename>")
sys.exit(1)
filename = sys.argv[1]
if not os.path.exists(filename):
print(f"File {filename} doesn't exist.")
sys.exit(1)
# Read file into database
with open(filename, "r") as file:
try:
parse_file(file, database)
print("Finished reading the file.")
except Exception as err:
print(f"Failed to read file {filename} with error {err}")
sys.exit(1)
# Write database to output file as JSON
output_filename = sys.argv[2]
with open(output_filename, "w+") as file:
try:
data = json.dumps(database)
file.write(data)
print(f"Finished writing to file {output_filename}")
except Exception as err:
print(f"Failed to read write to file {output_filename} with error {err}")
sys.exit(1)
def parse_file(file, database):
for line in file:
(word, thesaurus) = parse_line(line)
database[word] = thesaurus
def parse_line(line):
words = line.strip().split(",")
return (words[0], words[1:])
if __name__ == '__main__':
main()
I'm still a student -- I'm trying to improve my code readability & maintainability.
It is a commandline utility that can be called like:
make_database <input filename> <output filename>