Pythonで文字列中の各文字の出現回数を数える

Document 对象参考手册Python3 サンプル

Pythonでは、辞書を使用して文字列内の各文字の出現回数を数えることができます。文字列内の各文字を走査し、それを辞書のキーとすることで、各文字の出現回数を簡単に数えることができます。

サンプル

def count_characters(s):
    char_count = {}
    for char in s:
        if char in char_count:
            char_count[char] += 1
        else:
            char_count[char] = 1
    return char_count

# サンプル文字列
text = "hello world"
result = count_characters(text)
print(result)

コードの解説:

  1. count_characters(s)は、文字列を受け取る関数です。sパラメータとして。
  2. char_count = {}文字とその出現回数を格納するための空の辞書を初期化します。
  3. for char in s:文字列内の各文字を走査します。
  4. if char in char_count:現在の文字がすでに辞書に存在するかを確認します。
    • すでに辞書に存在する場合は、char_count[char] += 1その文字のカウントを1増やします。
    • 辞書に存在しない場合は、char_count[char] = 1その文字を辞書に追加し、カウントを1に初期化します。
  5. return char_count文字とその出現回数を含む辞書を返します。
  6. text = "hello world"サンプル文字列を定義します。
  7. result = count_characters(text)関数を呼び出し、サンプル文字列を渡します。
  8. print(result)結果を出力します。

出力結果:

サンプル

{'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}

この出力は、文字列 "hello world" 内の各文字の出現回数を示しています。例えば、文字 'l' は3回、文字 'o' は2回出現します。

Document 对象参考手册Python3 サンプル

その他の拡張