def sentence_stats(sentence): """ Prints out various statistics about the input sentence """ words = sentence.split() print_stats(words) def print_stats(words): """ Print out various statistics about the input list of words/strings """ print "Number of words: " + str(len(words)) print "Longest word: " + longest_word(words) print "Shortest word: " + shortest_word(words) print "Avg. word length: " + str(average_word_length(words)) # NOTE: if you want to try the example I did in class out # you'll need to download the file of English words from: # http://www.cs.middlebury.edu/~dkauchak/classes/cs150/examples/english.txt # def file_stats(filename): """ Prints out various statistics about the words in the file. File is assumed to be one word per line """ words = read_words(filename) print_stats(words) def read_words(filename): word_file = open(filename, "r") words = [] for line in word_file: # assuming one word per line words.append(line.strip()) word_file.close() return words def average_word_length(words): """Given a list of strings, get the average length of the strings in the list""" length_sum = 0 for word in words: length_sum += len(word) return float(length_sum)/len(words) def longest_word(words): """Given a list of strings, get the longest string/word in the list""" longest = "" for word in words: if len(word) > len(longest): longest = word return longest def shortest_word(words): """Given a list of strings, get the shortest string/word in the list""" shortest = words[0] for word in words: if len(word) < len(shortest): shortest = word return shortest