1 英文文件中单词、字母统计

题目:给定一个英文文本文件,统计各个字母的出现次数,单词总数,PD开头的单词出现字数,单词中间有逗号、句号、空格分割的字符串(不考虑其他)
思路:
1、<fstream>头文件的使用,包括ifstream、ostream与fstream类,其中包括成员函数is_open的使用;
2、使用map来记录26个字母的出现,也可以用unordered_map;
3、while(file >> ch),不断输入字符;
4、使用<cctype>头文件中的isalpha(ch)来判断ch是否是字母,是的话统计出现次数;
5、创建一个bool变量来判断是否是新单词出现,第一次置为true,若读的是字母,则置为false,一直等到读到非字母,再置为true,以此来统计单词的出现;
6、创建一个字符串word,记录读到的字母,如果isalpha(ch)为true,则word += ch;,否则将word清空,进入下一个新的单词统计。

注:<cctyoe>中的函数:

  • isalpha()用来判断一个字符是否为字母。
  • isalnum用来判断一个字符是否为数字或者字母,也就是说判断一个字符是否属于a~ z||A~ Z||0~9。
  • isdigit() 用来检测一个字符是否是十进制数字0-9。
  • islower()用来判断一个字符是否为小写字母,也就是是否属于a~z。
  • isupper()和islower相反,用来判断一个字符是否为大写字母。
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <cctype>

using namespace std;

int main() {
    string filename;
    cout << "Enter the filename: ";
    cin >> filename;

    ifstream file(filename);
    if (!file.is_open()) {
        cerr << "Error opening file: " << filename << endl;
        return 1;
    }

    map<char, int> LetterCount;
    int WordCount = 0;
    int pdWordCount = 0;
    string word;
    char ch;


    bool isNewWord = true;
    while (file >> ch) {
        if (isalpha(ch)) {
            LetterCount[ch]++;
            if (isNewWord) {
                WordCount++;
                isNewWord = false;
            }
            if (!word.empty() && word[0] == 'P' && word[1] == 'D') {
                pdWordCount++;
            }
            word += ch;
        }
        else {
            isNewWord = true;
            word.clear();
        }
    }
    file.close();

    cout << "Letter Count:" << endl;
    for (const auto& pair : LetterCount) {
        cout << pair.first << ": " << pair.second << endl;
    }
    cout << "Total Word Count: " << WordCount << endl;
    cout << "PD Word Count: " << pdWordCount << endl;
    return 0;
}
posted @ 2025-05-17 19:04  Y314Y  阅读(29)  评论(3)    收藏  举报