C++ 实现文本词频统计时如何移除map内单词附带的标点
现有代码的核心问题
- 标点判定逻辑完全错误:
ispunct接收单个字符作为入参,原代码直接将整数/字符串传入该函数,既无法通过编译,也无法实现单字符的标点识别 - 取值逻辑完全错位:原代码中
ispunct(M[it->first])传入的参数是M[it->first],也就是map中当前单词对应的整数计数值,并非存储单词的字符串对象,哪怕编译能通过,传int值给ispunct也完全偏离预期效果 - 元素擦除逻辑存在严重未定义行为:原代码在遍历
map的循环内调用string的erase方法时,错误传入了map的迭代器作为参数,同时遍历过程中直接修改map容器结构会导致迭代器失效,直接触发程序崩溃 - 处理时机完全错位:原代码是先将带标点的原始单词全部存入map完成词频统计,才尝试清除标点。这种处理方式下,
hello、hello.、hello!会被识别为三个独立单词分别计数,清除标点后也无法合并三者的计数,最终词频结果完全失真 - 缺失必要头文件:原代码直接使用
ispunct但没有引入<cctype>头文件,属于编译隐式依赖,在严格编译环境下会直接报错
正确实现流程
- 将标点清洗环节提前到文本读取阶段:每读取到一个原始单词,先对字符串首尾附着的标点字符做剔除,仅保留有效单词内容,清洗完成后再将有效单词存入vector,从根源上避免带标点的内容被纳入词频统计
- 单独封装标点清洗逻辑:遍历单词的首尾字符,逐个移除符合
ispunct判定的标点符号,注意传入ispunct的字符要转为unsigned char,避免有符号char值为负时触发未定义行为 - 完成清洗后再构建map统计词频,遍历map时直接输出清洗后的单词与对应计数即可,不需要再在遍历阶段额外修改map结构
修正后的可运行代码
#include <iostream> #include <string> #include <map> #include <algorithm> #include <vector> #include <fstream> #include <cctype> // 补充ispunct对应的标准头文件 using namespace std; void print_frequency(vector<string>&); // 封装单词清洗函数,剔除单词首尾附着的标点 string clean_word(string raw_word) { // 清除开头的标点 while (!raw_word.empty() && ispunct(static_cast<unsigned char>(raw_word.front()))) { raw_word.erase(raw_word.begin()); } // 清除结尾的标点 while (!raw_word.empty() && ispunct(static_cast<unsigned char>(raw_word.back()))) { raw_word.pop_back(); } return raw_word; } int main() { ifstream infile; string raw_word; vector<string> words; infile.open("words.txt"); if (infile.fail()) { cerr << "Can't open file\n"; exit(1); } // 读取文件时同步完成单词清洗 while (infile >> raw_word) { string cleaned = clean_word(raw_word); // 清洗后非空才存入容器,避免把纯标点的内容计入词频 if (!cleaned.empty()) { words.push_back(cleaned); } } print_frequency(words); } void print_frequency(vector<string>& words) { map<string, int> M; // 基于已经清洗干净的单词列表构建词频map for (size_t i = 0; i < words.size(); i++) { if (M.find(words[i]) == M.end()) M[words[i]] = 1; else M[words[i]]++; } // 直接遍历map输出,不需要额外处理标点 for (auto it = M.begin(); it != M.end(); it++) { cout << it->first << " " << it->second << endl; } }
内容的提问来源于stack exchange,提问作者Mr.Mafia
相关产品推荐
相关产品推荐

