2016.06.09
Jackal

import this

ある英文内に各アルファベットが何回出てくるかを数える
プログラムを書くとこんな感じになると思います。

# -*- coding: utf-8 -*-

sentence = """
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
"""

char_counter = {}
for char in sentence:
    if char.isalpha():
        char = char.lower()
        if char in char_counter:
            char_counter[char] += 1
        else:
            char_counter[char] = 1

for char in sorted(char_counter.keys()):
    print '%s: %d' % (char, char_counter[char])


ディクショナリーを使ってカウントする場合、すでに存在するキーか
どうかを調べて処理を分岐しないとエラーになるので

if char in char_counter:
    char_counter[char] += 1
else:
    char_counter[char] = 1


という醜い部分が存在するのですが、pythonにはこういった用途に適した
ビルトインのCounterというオブジェクトがあり、それをつかって書くとすっきりとします。

# -*- coding: utf-8 -*-

from collections import Counter

sentence = """
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
"""

char_counter = Counter()
for char in sentence:
    if char.isalpha():
        char_counter[char.lower()] += 1

for char in sorted(char_counter.keys()):
    print '%s: %d' % (char, char_counter[char])

美しいですね。

YI

一覧に戻る