We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Python Script

We've seen how simple it is to dockerize Go programs! That's part of the beauty of Go, the machine (or Docker image) running the program doesn't need the Go compiler installed. None of the following languages are easily deployed in the same way:

  • Python
  • JavaScript/TypeScript
  • Java
  • Ruby
  • PHP
  • C#
  • etc...

They all have runtime dependencies. To show you what I mean, let's Dockerize a little Python script.

Assignment

# Linux (or WSL)
sudo apt update
sudo apt install -y python3

# Mac OS
brew install python
python3 main.py

Run and submit the CLI tests from your working directory.

Python Code to Copy

def main():
    book_path = "books/frankenstein.txt"
    text = get_book_text(book_path)
    num_words = get_num_words(text)
    chars_dict = get_chars_dict(text)
    chars_sorted_list = chars_dict_to_sorted_list(chars_dict)

    print(f"--- Begin report of {book_path} ---")
    print(f"{num_words} words found in the document")
    print()

    for item in chars_sorted_list:
        if not item["char"].isalpha():
            continue
        print(f"The '{item['char']}' character was found {item['num']} times")

    print("--- End report ---")


def get_num_words(text):
    words = text.split()
    return len(words)


def sort_on(d):
    return d["num"]


def chars_dict_to_sorted_list(num_chars_dict):
    sorted_list = []
    for ch in num_chars_dict:
        sorted_list.append({"char": ch, "num": num_chars_dict[ch]})
    sorted_list.sort(reverse=True, key=sort_on)
    return sorted_list


def get_chars_dict(text):
    chars = {}
    for c in text:
        lowered = c.lower()
        if lowered in chars:
            chars[lowered] += 1
        else:
            chars[lowered] = 1
    return chars


def get_book_text(path):
    with open(path) as f:
        return f.read()


main()