Python 古典 100 の質問: 文字数を数える

質問: 文字列を入力し、その中に含まれる英語の文字、スペース、数字、その他の文字の数を数えてください。

方法 1:

str_input = input("请输入一行字符:")
count_letter, count_space, count_digits, count_other = 0, 0, 0, 0
for char in str_input:
    if char.isalpha():
        count_letter += 1
    elif char.isspace():
        count_space += 1
    elif char.isdigit():
        count_digits += 1
    else:
        count_other += 1
print("英文字母个数为:", count_letter)
print("空格个数为:", count_space)
print("数字个数为:", count_digits)
print("其他字符个数为:", count_other)

アイデア: for ループを使用して文字列内の各文字をたどり、それが英語の文字、スペース、数字、またはその他の文字に属しているかどうかを判断し、対応する数字を記録します。最後に結果を出力します。

利点: シンプルで理解しやすく、コードが少なくなります。

欠点: if-elif ステートメントが多く、コードが読みにくくなります。

方法 2:

str_input = input("请输入一行字符:")
count_letter = sum(1 for char in str_input if char.isalpha())
count_space = sum(1 for char in str_input if char.isspace())
count_digits = sum(1 for char in str_input if char.isdigit())
count_other = len(str_input) - count_letter - count_space - count_digits
print("英文字母个数为:", count_letter)
print("空格个数为:", count_space)
print("数字个数为:", count_digits)
print("其他字符个数为:", count_other)

アイデア: ジェネレータ式と sum 関数を使用して、文字がどのカテゴリに属する​​かを決定するプロセスを 1 行のコードに統合し、コードを簡素化します。

利点: コードが少なくなり、読みやすくなります。

欠点: ジェネレーター式が sum 関数内にネストされているため、若干読みにくくなります。

方法 3:

from collections import Counter

str_input = input("请输入一行字符:")
count_dict = Counter(str_input)
count_letter = count_dict.get("{}".format(chr(10))) - 1    # 减去回车符的个数
count_space = count_dict.get(" ")
count_digits = sum(1 for key in count_dict if key.isdigit())
count_other = len(str_input) - count_letter - count_space - count_digits
print("英文字母个数为:", count_letter)
print("空格个数为:", count_space)
print("数字个数为:", count_digits)
print("其他字符个数为:", count_other)

アイデア: Python 標準ライブラリの Counter カウンターを使用して、文字列内のすべての文字とその出現数を記録し、辞書の get メソッドを通じて英語の文字、スペース、数字、その他の文字の数を取得します。

利点: コードは簡潔で読みやすいです。

欠点: コレクション ライブラリをインポートする必要があるため、このライブラリに慣れていない場合は理解するのが難しいかもしれません。

まとめると、3 つの方法はいずれも英字、スペース、数字などの文字の数をカウントできますが、どの方法を選択するかは、主にプロジェクトの実際の状況と個人の好みによって異なります。

おすすめ

転載: blog.csdn.net/yechuanhui/article/details/132900123