import random
import re


def generate_unigram_sentence(word_list):
    """Generates a sentence using the unigram frequency table"""
    sentence = ''
    while True:
        rand = random.random()
        val_sum = 0
        for k, v in word_list.items():
            val_sum += v       # Words value is added to val_sum
            if val_sum > rand: # First word to surpass the random value is used
                if re.match(r'([\.\,\!\?\;\:\=\+\/\*\\]+)', k): # Prevent punct. spacing
                    sentence += k
                else:
                    sentence += ' ' + k
                break
        if re.search(r'([\.\!\?]+)', sentence): # Sentence is complete once it has proper punct.
            break
    sentence = sentence.strip()      # Strip whitespace for cleanliness
    sentence = sentence.capitalize() # Capitalize first letter
    return sentence