LoginSignup
12

More than 5 years have passed since last update.

Pythonで文字列からさくっと文字の出現頻度を数えるには?

Last updated at Posted at 2013-04-02
word = 'adsgsdfhsdgfhsdfggsfdgsdfgs'

とまあこんな感じの文字列があった場合、文字の出現頻度を数えたいけどややこしいことはしたくないなーと思ったので、どうやったらできるか考えてみた。

# 文字列から文字の集合を作る
char_set = { x for x in word }

# 出現頻度を辞書で表す
char_freq = { x : word.count(x) for x in char_set }

もっと本格的に文字列の出現頻度の算出やらをやるにはnltkとかが必要かと思いますが、これでもするっと腑に落ちる感があったので良し。


追記

Python2.7で追加されたCounterオブジェクトがそのものズバリな模様。yasuharu519さん情報ありがとうございます。

from collections import Counter

c = Counter(word)

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12