如何在C++中解析用户输入并忽略无意义词汇?
实现文本冒险游戏输入解析的实用方案
嘿,这个需求在文本冒险游戏开发里太普遍了!我来分享几个接地气的实现思路和代码示例,帮你轻松搞定输入解析中忽略停用词、提取关键指令的功能~
一、核心步骤拆解
整个输入解析流程可以分成3个关键环节:
- 输入预处理:统一格式、清理冗余内容(大小写、标点、多余空格)
- 停用词过滤:移除无意义的填充词汇(THE、TO等)
- 关键指令提取:从剩余词汇中识别动作+目标的核心结构
二、具体代码实现示例
1. 准备工作:定义停用词集合
首先,我们需要一个存储停用词的容器,用unordered_set查询效率最高:
#include <unordered_set> #include <string> #include <sstream> #include <cctype> #include <vector> #include <iostream> // 定义停用词集合,你可以根据游戏需求添加更多词汇 const std::unordered_set<std::string> stop_words = { "the", "to", "a", "an", "and", "of", "in", "on", "is", "it" };
2. 输入预处理函数:清理并分割单词
这个函数会把用户输入转成小写、去掉标点、分割成单个单词,避免大小写敏感和冗余符号干扰:
std::vector<std::string> preprocess_input(const std::string& input) { std::vector<std::string> words; std::string cleaned_input; // 1. 转小写并过滤非字母字符(保留空格用于分割) for (char c : input) { if (std::isalpha(c)) { cleaned_input += std::tolower(c); } else if (std::isspace(c)) { cleaned_input += c; } // 标点、数字等直接忽略 } // 2. 按空格分割成单词列表 std::istringstream iss(cleaned_input); std::string word; while (iss >> word) { words.push_back(word); } return words; }
3. 停用词过滤与指令提取
接下来过滤掉停用词,然后提取核心指令。这里假设游戏最常见的指令结构是「动作 + 目标」(比如GET DOG、MOVE LEFT):
void parse_command(const std::vector<std::string>& words) { std::vector<std::string> filtered_words; // 过滤停用词 for (const std::string& word : words) { if (stop_words.find(word) == stop_words.end()) { filtered_words.push_back(word); } } // 处理空指令情况 if (filtered_words.empty()) { std::cout << "抱歉,我没听懂你的指令,请换个说法试试!" << std::endl; return; } // 提取动作和目标 std::string action = filtered_words[0]; std::string target = (filtered_words.size() > 1) ? filtered_words[1] : ""; // 这里可以对接你的游戏逻辑,比如根据动作执行对应操作 std::cout << "识别到核心指令:动作[" << action << "],目标[" << target << "]" << std::endl; // 示例逻辑:处理常见动作 if (action == "get" || action == "take") { std::cout << "你尝试拾取" << target << "!" << std::endl; } else if (action == "move" || action == "go") { std::cout << "你向" << target << "方向移动!" << std::endl; } // 可以继续扩展更多动作类型... }
4. 主函数调用示例
int main() { std::string user_input; std::cout << "欢迎来到文本冒险游戏!输入你的指令(比如:get the dog):" << std::endl; while (std::getline(std::cin, user_input)) { auto processed_words = preprocess_input(user_input); parse_command(processed_words); std::cout << "\n请继续输入指令:" << std::endl; } return 0; }
三、进阶优化建议
- 同义词映射:比如用户输入"take"和"get"都表示拾取,可以加一个同义词表,把非标准动作统一成游戏内的标准指令(比如
std::unordered_map<std::string, std::string> synonyms = {{"take", "get"}, {"go", "move"}})。 - 多目标处理:如果用户输入"get the dog and key",可以扩展逻辑提取多个目标,支持批量操作。
- 模糊匹配:对拼写错误的指令(比如"gdt dog"),可以用编辑距离算法匹配最接近的有效指令,提升游戏容错性。
内容的提问来源于stack exchange,提问作者ty1
相关产品推荐
相关产品推荐

