📚 The CoCalc Library - books, templates and other resources
License: OTHER
"""This module contains a code example related to12Think Python, 2nd Edition3by Allen Downey4http://thinkpython2.com56Copyright 2015 Allen Downey78License: http://creativecommons.org/licenses/by/4.0/9"""1011from __future__ import print_function, division1213import random1415from bisect import bisect1617from analyze_book1 import process_file181920def random_word(hist):21"""Chooses a random word from a histogram.2223The probability of each word is proportional to its frequency.2425hist: map from word to frequency26"""27# TODO: This could be made faster by computing the cumulative28# frequencies once and reusing them.2930words = []31freqs = []32total_freq = 03334# make a list of words and a list of cumulative frequencies35for word, freq in hist.items():36total_freq += freq37words.append(word)38freqs.append(total_freq)3940# choose a random value and find its location in the cumulative list41x = random.randint(0, total_freq-1)42index = bisect(freqs, x)43return words[index]444546def main():47hist = process_file('158-0.txt', skip_header=True)4849print("\n\nHere are some random words from the book")50for i in range(100):51print(random_word(hist), end=' ')525354if __name__ == '__main__':55main()56575859