2016年8月27日土曜日

開発環境

Think Python (Allen B. Downey (著)、 O'Reilly Media)のChapter 13.(Case Study: Data Structure Selection)のExercises 13-6.(No. 3021)を取り組んでみる。

Exercises 13-6.(No. 3021)

コード(Emacs)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import string
import random


def get_words(filename, header=True):
    words = {}
    with open(filename) as f:
        flag = header
        for line in f:
            if flag:
                if line.startswith('***'):
                    flag = False
                continue
            for ch in string.punctuation:
                line = line.replace(ch, ' ')
            for word in line.split():
                word = word.strip(string.whitespace).lower()
                words[word] = words.get(word, 0) + 1
    return words

if __name__ == '__main__':
    book_title = 'History_of_a_Six_Weeks_Tour_by_Shelley_and_Shelley.txt'
    words_freq = get_words(book_title)
    word_list = []
    for word, freq in words_freq.items():
        word_list += [word] * freq

    for _ in range(10):
        print(random.choice(word_list))

入出力結果(Terminal, IPython)

$ ./sample7.py
somewhat
and
seems
s
of
over
the
troyes
continued
unfathomable
$

0 コメント:

コメントを投稿

Comments on Google+: