在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}')
方法二:使用第三方库
from collections import Counter打开文档并读取内容with open('document.txt', 'r') as file:content = file.read()使用Counter统计字母出现次数letter_count = Counter(content.lower())打印字母出现次数for letter, count in sorted(letter_count.items()):print(f'{letter}:{count}')
方法三:使用内置函数
输入的字符串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."计算英文字母出现的频率result = * 26for c in input_str:if c.isalpha(): 必须是26个字母之一c = c.lower() 转换为小写字母result[ord(c) - ord('a')] += 1输出结果for i, count in enumerate(result):print(f'字母 {chr(i + ord("a"))}:{count}')
以上方法可以帮助你统计文本中每个字母出现的次数。请选择适合你需求的方法进行尝试
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/30432.html