def createWordList(textFile): #Open the input file myFile = open(textFile,"r") #Read the file fileText = myFile.read() #Close the file myFile.close() #Clean up the test badChars = ".,!?;(){}:" for badChar in badChars: fileText=fileText.replace(badChar,"") #Deal with the dash fileText = fileText.replace("-"," ") #Lowercase all words fileText = fileText.lower() listOfWords = fileText.split() return(listOfWords) def countUniqueWords(textFile): # Get the big word list wordList = createWordList(textFile) # Unique word list uniqueWordList = [] for word in wordList: #If not in unique list if not word in uniqueWordList: uniqueWordList.append(word) return len(uniqueWordList) def countTimes(textFile): # Get the big word list wordList = createWordList(textFile) # New dictionary newDict = {} for word in wordList: #If not in dictionary if not word in newDict: newDict[word] = 1 else: newDict[word] += 1 #return newDict #####print things out nicely (not in order) for word in newDict: print(word,"->",newDict[word]) #####sorting by key (word) wordList = list(newDict.keys()) wordList.sort() #Use a for loop to get each alphabetical word for word in wordList: print(word,"->",newDict[word]) #####sorting by value (frequency) #Make a list of miniLists: [[value,key], [value,key], ....] bigList = [] for word in newDict: bigList.append([newDict[word],word]) bigList.sort(reverse=True) #Now the bigList is sorted. Get out each small list. for littleList in bigList: print(littleList[1], "->", littleList[0])