Pythonでいろいろやってみる

Pythonを使った画像処理や機械学習などの簡単なプログラムを載せています。

文字列にアルファベットがそれぞれ何個含まれているか数える

文字列にアルファベットの小文字(a-z)と大文字(A-Z)がそれぞれ何個ずつ出現するか数えます。for文で文字コードを回して.count()メソッドにより出現回数をカウントします。

使ったメソッド
  • .count() : 文字列の出現回数を求める
環境
  • windows10 home
  • Anaconda 3/ jupyter notebook 5.6.0
  • Python 3.7.0
準備  

カウント対象の文字列strに、アメリカンセンターJAPANのサイトに掲載されているリンカーン大統領のゲティスバーグ演説をコピーさせていただきました。
アメリカンセンターJAPAN>>Gettysburg Address (1863)

コード
str='Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that the nation might live. It is altogether fitting and proper that we should do this.But, in a larger sense, we can not dedicate - we can not consecrate - we can not hallow - this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us - that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion - that we here highly resolve that these dead shall not have died in vain - that this nation, under God, shall have a new birth of freedom - and that government of the people, by the people, for the people, shall not perish from the earth.'
for i,j in zip(range(97, 97+26),range(65, 65+26)):
    print(chr(i),':',str.count(chr(i)),'  ',chr(j),':',str.count(chr(j)))
実行結果

小文字、大文字それぞれのアルファベットの出現回数が表示されます。'e'が最も多く166回、次が't'で123回でした。

a : 101 A : 0
b : 13 B : 1
c : 31 C : 0
d : 58 D : 0
e : 166 E : 0
f : 26 F : 1
g : 27 G : 1
h : 80 H : 0
i : 65 I : 3
j : 0 J : 0
k : 3 K : 0
l : 41 L : 1
m : 13 M : 0
n : 76 N : 1
o : 93 O : 0
p : 15 P : 0
q : 1 Q : 0
r : 79 R : 0
s : 44 S : 0
t : 123 T : 2
u : 21 U : 0
v : 24 V : 0
w : 26 W : 2
x : 0 X : 0
y : 10 Y : 0
z : 0 Z : 0

以下のサイトを参考にさせていただきました

[python] いろいろな文字種のリストを作成

ブログランキングに参加しています

にほんブログ村 IT技術ブログへ
にほんブログ村