如何统计字符串中每个字符出现的次数并按顺序打印

443 阅读3分钟

给定一个字符串,统计每个字符出现的次数,并按字符在字符串中出现的顺序打印出来。字符的统计结果中,需要统计大小写字母为同一个字符,例如:'A' 和 'a' 都被统计为同一个字符。而且,统计结果中不应出现重复的字符。

2、解决方案

(1) 使用 collections.Counter

Python 中的 collections.Counter 类可以统计字符串中每个字符出现的次数。下面是使用 collections.Counter 类解决这个问题的代码示例:

from collections import Counter

def count_characters(text):
  # 使用 `Counter` 类统计字符串中每个字符出现的次数
  counts = Counter(text)

  # 使用 `items()` 方法获取字符及其出现次数的元组列表
  character_counts = counts.items()

  # 使用 `sorted()` 函数对元组列表按字符的顺序进行排序
  sorted_character_counts = sorted(character_counts, key=lambda x: x[0])

  # 使用 `print()` 函数打印字符及其出现次数
  for character, count in sorted_character_counts:
    print(f"{character}: {count}")

# 获取用户的输入
text = input("Enter a string: ")

# 统计字符串中每个字符出现的次数并按顺序打印
count_characters(text)

(2) 使用 OrderedCounter

OrderedCounter 类是 Counter 类的子类,它可以保证字符及其出现次数的输出顺序与字符在字符串中出现的顺序一致。下面是使用 OrderedCounter 类解决这个问题的代码示例:

from collections import OrderedDict, Counter

class OrderedCounter(Counter, OrderedDict):
  def __repr__(self):
    return '%s(%r)' % (self.__class__.__name__, OrderedDict(self))

  def __reduce__(self):
    return self.__class__, (OrderedDict(self),)

def count_characters(text):
  # 使用 `OrderedCounter` 类统计字符串中每个字符出现的次数
  counts = OrderedCounter(text)

  # 使用 `items()` 方法获取字符及其出现次数的元组列表
  character_counts = counts.items()

  # 使用 `print()` 函数打印字符及其出现次数
  for character, count in character_counts:
    print(f"{character}: {count}")

# 获取用户的输入
text = input("Enter a string: ")

# 统计字符串中每个字符出现的次数并按顺序打印
count_characters(text)

(3) 使用 collections.defaultdict

Python 中的 collections.defaultdict 类可以创建一个字典,当字典中不存在某个键时,会自动创建该键并将其值设置为默认值。下面是使用 collections.defaultdict 类解决这个问题的代码示例:

from collections import defaultdict

def count_characters(text):
  # 使用 `defaultdict` 类创建一个字典,并将默认值设置为 0
  counts = defaultdict(int)

  # 遍历字符串中的每个字符
  for character in text:
    # 将字符作为字典的键,并将该键对应的值加 1
    counts[character] += 1

  # 将字典中的键值对按字符的顺序排序
  sorted_character_counts = sorted(counts.items(), key=lambda x: x[0])

  # 使用 `print()` 函数打印字符及其出现次数
  for character, count in sorted_character_counts:
    print(f"{character}: {count}")

# 获取用户的输入
text = input("Enter a string: ")

# 统计字符串中每个字符出现的次数并按顺序打印
count_characters(text)

(4) 使用正则表达式

Python 中的正则表达式可以匹配字符串中的特定模式。下面是使用正则表达式解决这个问题的代码示例:

import re

def count_characters(text):
  # 使用正则表达式匹配字符串中的所有字符
  characters = re.findall(r".", text)

  # 使用 `collections.Counter` 类统计字符出现的次数
  counts = Counter(characters)

  # 使用 `items()` 方法获取字符及其出现次数的元组列表
  character_counts = counts.items()

  # 使用 `sorted()` 函数对元组列表按字符的顺序进行排序
  sorted_character_counts = sorted(character_counts, key=lambda x: x[0])

  # 使用 `print()` 函数打印字符及其出现次数
  for character, count in sorted_character_counts:
    print(f"{character}: {count}")

# 获取用户的输入
text = input("Enter a string: ")

# 统计字符串中每个字符出现的次数并按顺序打印
count_characters(text)