#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 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): dict_of_counts = {} # initialize counters for letter in 'abcdefghijklmnopqrstuvwxyz': dict_of_counts[letter] = 0 # count words for word in word_list: dict_of_counts[word[0]] += 1 return dict_of_counts 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 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ while True: letter = input('Enter a letter: ') letter = letter.lower() if len(letter) == 1 and letter.isalpha(): break total_words = sum(counts.values()) percent_for_letter = (counts[letter]/total_words) * 100 print() print(counts[letter], 'of the words start with', letter + '.') print('That is {:5.2f}% of all words.'.format(percent_for_letter)) print()