import re
import time

infile = open('mobydick-chap1.txt', 'r')

wholefilestr = infile.read()

infile.close()

wholefilestr = wholefilestr.strip()

punctuation = '[\s\$\*!.,:;\[\]{}&<>\?()\'\"\-]'
# some of the characters need a \ because without them they would be interpreted 
# differently as part of the regular expression in square brackets
# e.g. \s means whitespace, whereas s means the letter s

wordlist = re.split(punctuation, wholefilestr)

count = 0
for word in wordlist:
    if word != '':
        count += 1

outfile = open('wordoutput.txt', 'w')

outfile.write('There are ' + str(count) + ' words in chapter 1 of Moby Dick')

outfile.close()

print(f'There are {count} words in chapter 1 of Moby Dick')


wordcounts = {}

for word in wordlist:
    if word != '':
        if word in wordcounts:
            wordcounts[word] += 1
        else:
            wordcounts[word] = 1

for word in wordcounts:
    print(f'{word} appears {wordcounts[word]} times in the chapter.')
    time.sleep(1)
    
