PYTHON MEBY

Pythonで文字列の出現回数をカウント(count)

この記事ではPythonで文字列の中に特定の文字列が出現する回数を数える方法について解説します。count()メソッドの使い方や、より高度な検索方法についても説明します。

目次

count()メソッドによる単純なカウント

Pythonの文字列型は、count()メソッドを使って特定の文字列の出現回数を簡単に数えることができます。

text = "apple banana apple orange apple"
count = text.count("apple")
print(count)  # 出力: 3

この例では、変数textに格納された文字列の中で"apple"という文字列が3回出現しているので、3が出力されます。

count()メソッドのオプション引数

count()メソッドは、オプション引数として開始位置と終了位置を指定できます。これにより、文字列の一部分だけを対象にカウントできます。

text = "apple banana apple orange apple"
count = text.count("apple", 0, 15) # 0から15文字目までの範囲でカウント
print(count)  # 出力: 2

この例では、0文字目から15文字目までの範囲で"apple"をカウントしているので、2が出力されます。

text = "apple apple apple"
count1 = text.count('apple')
count2 = text.count('apple', 1, 10)
print(count1) #出力:3
print(count2) #出力:2

正規表現を使った高度なカウント

より複雑なパターンを検索したい場合は、正規表現モジュールreを使うと便利です。

import re
text = "apple apple Apple APPLE"
count = len(re.findall(r"apple", text, re.IGNORECASE))
print(count) #出力:4

この例では、re.findall()を使って、大文字小文字を区別せずに"apple"の出現回数をカウントしています。re.IGNORECASEフラグを指定することで大文字小文字を区別しない検索ができます。

import re
text = "apple, apple, apple"
count = len(re.findall(r"apple", text))
print(count) #出力:3

実践例

例えば、テキストファイル内の特定の単語の出現回数を数える場合などに応用できます。

import re
with open("sample.txt", "r", encoding="utf-8") as f:
    text = f.read()
    count = len(re.findall(r"python", text, re.IGNORECASE))
    print(f"'python'の出現回数: {count}")

sample.txtファイルが存在し、適切なエンコーディングを指定する必要があります。 エラー処理を追加するとより堅牢なコードになります。

関連記事