C++ 聊天机器人:自动识别语料库并智能回复
以下是一个使用 C++ 编写的简单聊天机器人的示例代码:
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <map>
#include <algorithm>
std::map<std::string, std::string> loadConfig(const std::string& filename) {
std::map<std::string, std::string> config;
std::ifstream file(filename);
std::string line;
while (std::getline(file, line)) {
std::istringstream iss(line);
std::string question, answer;
if (std::getline(iss, question, '=') && std::getline(iss, answer)) {
config[question] = answer;
}
}
return config;
}
std::vector<std::string> splitSentences(const std::string& input) {
std::vector<std::string> sentences;
std::istringstream iss(input);
std::string sentence;
while (std::getline(iss, sentence, '.') || std::getline(iss, sentence, ',')) {
sentences.push_back(sentence);
}
return sentences;
}
std::string findBestMatch(const std::string& input, const std::map<std::string, std::string>& config) {
std::string bestMatch;
int maxMatchCount = 0;
for (const auto& entry : config) {
const std::string& question = entry.first;
int matchCount = 0;
for (char c : input) {
if (std::tolower(c) == std::tolower(question[matchCount])) {
matchCount++;
if (matchCount == question.size()) {
return entry.second;
}
}
}
if (matchCount > maxMatchCount) {
maxMatchCount = matchCount;
bestMatch = entry.second;
}
}
return bestMatch;
}
int main() {
std::map<std::string, std::string> config = loadConfig('config.ini');
std::string userInput;
std::cout << '请输入问题: ';
std::getline(std::cin, userInput);
std::vector<std::string> sentences = splitSentences(userInput);
for (const std::string& sentence : sentences) {
std::string answer = findBestMatch(sentence, config);
std::cout << '回答: ' << answer << std::endl;
}
return 0;
}
上述代码假设 'config.ini' 文件与可执行文件位于同一目录下,且 'config.ini' 的格式为每行一个问题和答案,以等号 = 分隔,例如:
你好=你好啊
天气怎么样=今天天气晴朗
运行程序后,用户可以输入问题,程序将根据输入的问题在 'config.ini' 中寻找匹配程度最高的问题,并输出相应的回答。用户输入的问题可以以中文或英文逗号或句号作为分隔,程序会逐句判断并输出断好句的回答。
原文地址: https://www.cveoy.top/t/topic/jSs 著作权归作者所有。请勿转载和采集!