C++移除停用词功能实现遇阻,嵌套循环逻辑问题求助
解决C++停用词过滤的问题
先梳理你代码里的几个关键问题:
1. 停用词列表的低级错误
stop_words数组里的"is "多了一个空格,这会导致输入中的正常"is"永远无法匹配到停用词,先把这个空格去掉。
2. 单词拆分逻辑的缺陷
- 统计单词数的循环没考虑连续空格的情况,比如输入多个空格会错误增加单词计数
- 手动遍历字符拆分单词的逻辑鲁棒性差,用
stringstream拆分单词会更简洁可靠
3. 停用词过滤的核心逻辑错误
你当前的嵌套循环逻辑是:只要当前单词和某一个停用词不相等,就把它存入out数组。但哪怕这个单词是停用词,只要和最后一个停用词不匹配,还是会被错误保留。正确逻辑应该是:只有当单词和所有停用词都不匹配时,才保留它。
4. 输出逻辑的问题
最后固定循环10次输出out数组,不管实际有效单词数量,会输出大量空字符串。
修正后的完整代码
#include <iostream> #include <string> #include <sstream> using namespace std; void removeStopWords(string str); int main() { string str; cout << "String : "; getline(cin, str); removeStopWords(str); return 0; } void removeStopWords(string str) { // 修正停用词的空格问题 string stop_words[10] = {"this", "is", "a", "are", "and", "as", "at", "do", "hence", "your"}; string original_words[1000]; int word_count = 0; // 用stringstream拆分单词,自动处理空格分隔 stringstream ss(str); string word; while (ss >> word) { original_words[word_count++] = word; } // 过滤并输出非停用词 for (int i = 0; i < word_count; i++) { bool is_stop = false; // 遍历停用词列表检查匹配 for (int j = 0; j < 10; j++) { if (original_words[i] == stop_words[j]) { is_stop = true; break; // 找到匹配就跳出循环,无需继续检查 } } if (!is_stop) { cout << original_words[i] << " "; } } cout << endl; }
进阶优化方案
如果你的C++版本支持,用unordered_set存储停用词可以把查找效率从O(n)降到O(1),代码也更简洁:
#include <iostream> #include <string> #include <sstream> #include <unordered_set> using namespace std; void removeStopWords(string str); int main() { string str; cout << "String : "; getline(cin, str); removeStopWords(str); return 0; } void removeStopWords(string str) { unordered_set<string> stop_words = {"this", "is", "a", "are", "and", "as", "at", "do", "hence", "your"}; stringstream ss(str); string word; while (ss >> word) { // 检查单词是否不在停用词集合中 if (stop_words.find(word) == stop_words.end()) { cout << word << " "; } } cout << endl; }
内容的提问来源于stack exchange,提问作者Mxneeb
相关产品推荐
相关产品推荐

