開発環境
- macOS Sierra - Apple (OS)
 - Emacs (Text Editor)
 - Python 3.5 (プログラミング言語)
 
Exercises for Programmers: 57 Challenges to Develop Your Coding Skills (Brian P. Hogan 著、Pragmatic Bookshelf)のChapter 8(Working with Files)、46(Word Frequency Finder)を取り組んでみる。
46(Word Frequency Finder)
コード(Emacs)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import string
import collections
import requests
import bs4
import matplotlib.pyplot as plt
filename = 'words.txt'
print('words.text')
words = {}
with open(filename) as f:
    for line in f:
        for word in line.split():
            word = word.strip().lower()
            words[word] = words.get(word, 0) + 1
l = max(map(len, words.keys())) + 1
fmt = '{{0:{0}}}: {{1}}'.format(l)
for word in sorted(words):
    print(fmt.format(word, words[word] * '*'))
url = 'http://shakespeare.mit.edu/macbeth/full.html'
html = requests.get(url)
bs_obj = bs4.BeautifulSoup(html.text, 'html.parser')
text = bs_obj.text
words = []
for line in text.split('\n'):
    for ch in string.punctuation:
        line = line.replace(ch, ' ')
    words += list(
        filter(lambda word: word != '',
               map(lambda word: word.strip().lower(),
                   [word for word in line.split()])))
counter = collections.Counter(words)
words = counter.most_common(100)
l = max(map(lambda x: len(x[0]), words)) + 1
fmt = '{{0:{0}}}: {{1}}'.format(l)
print(url)
for word, count in sorted(words):
    print(fmt.format(word, count * '*'))
fig = plt.figure(figsize=(6, len(words) / 3))
fig.subplots_adjust(left=0.25)
words = sorted(words, reverse=True)
labels = []
data = []
for word, count in words:
    labels.append(word)
    data.append(count)
num_bars = len(labels)
positions = range(1, num_bars + 1)
plt.barh(positions, data, align='center')
plt.yticks(positions, labels)
plt.xlabel('Frequency')
plt.ylabel('Word')
plt.title("Word Frequency (Shakespeare's Macbeth)")
plt.grid()
plt.savefig('sample46.svg')
with open('shakespeare_macbeth.txt', 'w') as f:
    print(text, file=f, end='')
plt.show()
入出力結果(Terminal, IPython)
$ ./sample46.py words.text badger : ******* mushroom : ** snake : * http://shakespeare.mit.edu/macbeth/full.html a : ************************************************************************************************************************************************************************************************************************************************************ all : *********************************************************************************************************** and : ************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************* are : ************************************************************************* as : ****************************************************************************************** at : ***************************************************** banquo : **************************************************************************** be : ******************************************************************************************************************************************** but : **************************************************************************************************************************** by : ************************************************ come : ****************************************************** d : ********************************************************************************************************************************************************* did : ***************************************** do : ************************************************************************************ done : ************************************** duncan : ************************************* enter : ************************************************************************ fear : ************************************ first : ******************************************************** for : **************************************************************************************************************** from : ********************************************************* good : **************************************************** had : ********************************** hath : ************************************************** have : ***************************************************************************************************************************** he : ***************************************************************************************************************************** her : ******************************************** here : *********************************************** him : ******************************************************************************************* his : ************************************************************************************************************************************************** i : ************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************* if : ********************************************* in : *************************************************************************************************************************************************************************************************************** is : ************************************************************************************************************************************************************************************************ it : ********************************************************************************************************************************************************** king : ************************************ know : *********************************** lady : *********************************************************************************************** let : ****************************************** like : ****************************************** ll : ************************************************ lord : *************************************** macbeth : ************************************************************************************************************************************************************************************************************************************************************************************************ macduff : *********************************************************************************************************** make : *************************************** malcolm : *********************************************************** man : ************************************** me : **************************************************************************************************************** more : **************************************************** murderer : *********************************** must : *********************************** my : ************************************************************************************************************************************************************************************************ night : *************************************** no : ******************************************************************* not : ********************************************************************************************************************************************************************* now : ***************************************************** o : ********************************************* of : ******************************************************************************************************************************************************************************************************************************************************************************************************************************************************* on : ****************************************************************** or : ************************************ our : *********************************************************************************************************************** ross : ***************************************************** s : ****************************************************************************************************************************************************************************************************** say : ***************************************** shall : ******************************************************************* should : ***************************************** so : ************************************************************************************************ t : ******************************************* that : ********************************************************************************************************************************************************************************************************************************************* the : ************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************ thee : ************************************************************* their : ************************************************************* them : ************************************************** then : ************************************ there : ***************************************************** they : ************************************************************************ this : ******************************************************************************************************* thou : ************************************************************************************************ thy : **************************************************** time : ********************************************* tis : ************************************* to : ******************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************* upon : ************************************************************** us : ******************************************************* was : *********************************************** we : ************************************************************************************************* well : *********************************** were : **************************************** what : ******************************************************************************************************************** when : **************************************** where : ************************************* which : ******************************************************************************** who : ************************************************* will : ************************************************************************* witch : **************************************************** with : ********************************************************************************************************************************************************** would : *********************************************** yet : ********************************************************* you : *************************************************************************************************************************************************************************************************************** your : ************************************************************************************************************************* $
0 コメント:
コメントを投稿