2 . 编写一个程序,统计某个文本文件中字母、数字和其他字符的个数,文件名从键盘输入。
时间: 2023-11-07 18:08:34 浏览: 49
以下是 Python 代码实现:
```python
filename = input("请输入文件名:")
with open(filename, 'r') as file:
content = file.read()
letter_count = 0
digit_count = 0
other_count = 0
for char in content:
if char.isalpha():
letter_count += 1
elif char.isdigit():
digit_count += 1
else:
other_count += 1
print("字母个数:", letter_count)
print("数字个数:", digit_count)
print("其他字符个数:", other_count)
```
首先,程序会从用户那里获取文件名,然后打开文件并读取其中的内容。
接下来,程序遍历文本文件中的每个字符,使用 `isalpha()` 函数判断字符是否为字母,使用 `isdigit()` 函数判断字符是否为数字,如果都不是,则将其视为其他字符。
最后,程序输出字母、数字和其他字符的个数。
相关问题
2 . 编写一个程序,统计某个文本文件中字母、数字和其他字符的个数,文件名从键盘输入。用dev.c++
以下是使用 C++ 语言编写的程序,可以统计某个文本文件中字母、数字和其他字符的个数:
```cpp
#include <iostream>
#include <fstream>
#include <ctype.h>
using namespace std;
int main()
{
char filename[100];
cout << "请输入文件名:";
cin >> filename;
ifstream fin(filename); // 打开文件
if (!fin.good())
{
cout << "无法打开文件!" << endl;
return 0;
}
int letters = 0, digits = 0, others = 0;
char ch;
while (fin.get(ch))
{
if (isalpha(ch)) // 判断是否为字母
letters++;
else if (isdigit(ch)) // 判断是否为数字
digits++;
else // 其他字符
others++;
}
fin.close(); // 关闭文件
cout << "字母个数:" << letters << endl;
cout << "数字个数:" << digits << endl;
cout << "其他字符个数:" << others << endl;
return 0;
}
```
程序首先要求用户输入文件名,然后打开文件进行读取。在读取过程中,逐个字符判断其是字母、数字还是其他字符,并统计它们的个数。最后输出结果并关闭文件。
编写一个程序,统计某个文本文件中字母、数字和其他字符的个数,文件名从键盘输入。
好的,以下是C++程序的代码实现:
```c++
#include <iostream>
#include <fstream>
using namespace std;
int main() {
string filename;
cout << "请输入文件名:" << endl;
getline(cin, filename);
ifstream file(filename);
if (!file) {
cout << "打开文件失败!" << endl;
return 1;
}
int letter_count = 0, digit_count = 0, other_count = 0;
char ch;
while (file.get(ch)) { // 从文件中读取一个字符
if (isalpha(ch)) { // 如果是字母
letter_count++;
} else if (isdigit(ch)) { // 如果是数字
digit_count++;
} else { // 其他字符
other_count++;
}
}
file.close();
cout << "字母个数:" << letter_count << endl;
cout << "数字个数:" << digit_count << endl;
cout << "其他字符个数:" << other_count << endl;
return 0;
}
```
以上代码中,我们首先使用 `getline` 函数从键盘输入文件名,并且打开文件进行读取。在读取文件时,我们使用一个循环不断读取文件中的字符,并且使用 `isalpha` 函数判断是否为字母、使用 `isdigit` 函数判断是否为数字以及其他字符。最后关闭文件,并输出字母个数、数字个数和其他字符个数。
希望能够帮到你!