#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # string and word list definitions #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def scrub(word): return word.strip().lower() def load_word_list(filename='dictionary.txt'): word_file = open(filename, 'r') word_list = [] for word in word_file: word_list.append( scrub(word) ) return word_list def count_words(word_list): list_of_counts = [0] * 26 for word in word_list: index = position_for(word[0]) list_of_counts[index] += 1 return list_of_counts def position_for(ch): index = ord(ch) - ord('a') # index = 'abcdefghijklmnopqrstuvwxyz'.find(letter) return index words = load_word_list() counts = count_words(words) print('The list "counts" contains the number of words by first letter:') print(counts, end='\n\n') #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # solution to the exercise #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def look_up(letter, count_list): index = ord(letter) - ord('a') # index = 'abcdefghijklmnopqrstuvwxyz'.find(letter) return count_list[index] while True: letter = input('Enter a letter: ') letter = letter.lower() if len(letter) == 1 and letter.isalpha(): break total_words = sum(counts) words_for_letter = look_up(letter, counts) percent_for_letter = (words_for_letter/total_words) * 100 print() print(words_for_letter, 'of the words start with', letter + '.') print('That is {:5.2f}% of all words.'.format(percent_for_letter)) print()