在Python中统计字母频率可以通过以下几种方法实现:
方法一:使用纯Python
```python
打开文档并读取内容
with open('document.txt', 'r') as file:
content = file.read()
初始化字母计数器
letter_count = {}
遍历文档内容
for char in content:
if char.isalpha(): 判断是否为字母
char = char.lower() 统一转换为小写字母
letter_count[char] = letter_count.get(char, 0) + 1 更新字母计数
按字母顺序打印每个字母及其出现的次数
for letter, count in sorted(letter_count.items()):
print(f'{letter}:{count}')
方法二:使用第三方库
```python
from collections import Counter
输入的字符串
input_str = "The First-ever Open-water Beluga Sanctuary Will Welcome Two Adorable Whales in June, Adorable beluga whales are a popular attraction to aquariums around the world, but like many other wild animals, they also risk losing their habitats due to human intervention such as population growth, new buildings along the coastline, fishing, and other problems that sea creatures face."
计算英文字母出现的频率
def calc_statistic(input_str):
result = * 26 构建结果列表
for c in input_str:
if c.isalpha(): 必须是26个字母之一
c = c.lower() 转换为小写字母
result[ord(c) - ord('a')] += 1 更新字母计数
return result
输出结果
print("字母出现的频率:")
for i, count in enumerate(calc_statistic(input_str)):
print(f"字母 {chr(i + ord('a'))}: {count}")
方法三:使用`collections.Counter`类
```python
from collections import Counter
输入的字符串
input_str = "The First-ever Open-water Beluga Sanctuary Will Welcome Two Adorable Whales in June, Adorable beluga whales are a popular attraction to aquariums around the world, but like many other wild animals, they also risk losing their habitats due to human intervention such as population growth, new buildings along the coastline, fishing, and other problems that sea creatures face."
计算英文字母出现的频率
def calc_statistic(input_str):
return Counter(c.lower() for c in input_str if c.isalpha())
输出结果
print("字母出现的频率:")
for letter, count in calc_statistic(input_str).items():
print(f"{letter}: {count}")
以上方法可以帮助你统计文本中每个字母出现的频率。请根据你的需求选择合适的方法