python:编写程序,统计一个文本文件中出现的大写字母和它们出现的次数,并输出.
时间: 2023-05-18 15:02:43 浏览: 90
以下是 Python 代码,可以实现统计一个文本文件中出现的大写字母及其出现次数的功能:
```python
import string
filename = "text.txt"
uppercase_count = {}
with open(filename, "r") as file:
for line in file:
for char in line:
if char in string.ascii_uppercase:
if char in uppercase_count:
uppercase_count[char] += 1
else:
uppercase_count[char] = 1
for char, count in uppercase_count.items():
print(char, count)
```
这个程序会读取名为 `text.txt` 的文本文件,并统计其中出现的大写字母及其出现次数。程序使用了 Python 内置的 `string` 模块,其中的 `ascii_uppercase` 常量包含了所有的大写字母。程序首先创建了一个空字典 `uppercase_count`,用于存储每个大写字母出现的次数。然后,程序逐行读取文本文件,并逐个字符地检查是否为大写字母。如果是,就在 `uppercase_count` 中增加该字母的出现次数。最后,程序遍历 `uppercase_count` 中的每个键值对,并输出字母及其出现次数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)