import nltk
import pickle, random

print('Loading...')

# [A] Open one of your pickled bigram frequency distributions here
#  and load it to a variable named w1w2f.
# Make sure to close your pickle file.
# YOUR CODE BELOW: 


# [B] Choose your title.
# UNCOMMENT ONE OF THE TWO BELOW: 
title = 'Bible Speak'
title = 'Jane Austen Speak'

# The rest the code below is the interactive portion of the program.
# Don't edit below! 

print('Welcome to', title+'.')
print('Type in "EXIT" (all caps) to exit the program.')
word = input('Give me the first word: ').strip()

sent = ""
done = False

while not done :
    if word == 'EXIT' :
        done = True
    elif word.lower() in w1w2f :
        word = word.lower()
        special = {';', ',', '.', ':', '!', '?', "n't", "'s", "'d", "'m", "'re", "'ve", "'ll", "..."}
        if word in special :
            sent += word
        else:
            sent += ' '+word
        print('---------------------')
        print('Chosen word is "'+word+'". Your sentence(s) so far:')
        print('"'+sent.lstrip()+'"')
        print('---------------------')
        
        w2f = w1w2f[word]
        print('Following "' + word +'", top candidates for the next word are:')    
        topcand = w2f.most_common(10)
        for i in range(len(topcand)) :
            (w2, rawfreq) = topcand[i]
            prob  = w2f.freq(w2)
            probperc = '{:.2%}'.format(prob)            # String formatting: look it up. 
            print(' ['+str(i+1)+']', w2, '('+str(rawfreq)+', '+probperc+')', sep='\t')
            
        word = input('Type in the next word (or hit ENTER to randomly select from [1-10]): ').strip()
        if word == '':
            if len(topcand)>0 :
                (word, count) = random.choice(topcand)   # random choice function
            else :
                done = True
    else :
        print('Sorry, that word is not in our bigrams.')
        done = True

print('---------------------')
print('Your generated passage:')
print('"'+sent.lstrip()+'"')
print('---------------------')
print('Thank you for playing', title+'.')