''' Generate random text based on a sample text file make sure to have a .txt file saved in the same folder try running: Macbeth = createDictionary('Macbeth.txt') generateText(Macbeth, 25) ''' import random def createDictionary(fileName): a = open(fileName) text = a.read() a.close() listOfWords = text.split() d = {} prevWord = '$' for i in listOfWords: if prevWord[-1] in '?!.': prevWord='$' d[prevWord] += [i] elif prevWord not in d: d[prevWord] = [i] else: d[prevWord] += [i] prevWord = i return d def generateText(wordDict,numWords): words = '' prevWord='$' keys = list(wordDict.keys()) while numWords > 0: if words == '' or words[-2] in '?!.': newWord=str(wordDict['$'][random.choice(range(len(wordDict['$'])))]) words+=newWord+' ' else: newWord=str(wordDict[prevWord][random.choice(range(len(wordDict[prevWord])))]) words+=newWord+' ' numWords-=1 prevWord=newWord print(words)