C++ 简单聊天机器人实现:基于语料库的匹配问答
以下是一个使用 C++ 编写的简单聊天机器人示例,该机器人通过读取配置文件 config.ini 中的语料库,根据用户输入的问题找到与之匹配程度最高的语料库问题,并输出相应的答案。此外,程序可以识别用户输入的中文或英文句子,并分别判断每一句,给出对应答案。
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
std::string trim(const std::string& str) {
size_t first = str.find_first_not_of("
");
size_t last = str.find_last_not_of("
");
if (first == std::string::npos || last == std::string::npos)
return "";
return str.substr(first, last - first + 1);
}
std::string findBestMatch(const std::string& question, const std::vector<std::string>& questions) {
std::string bestMatch;
int bestMatchScore = 0;
for (const std::string& q : questions) {
int score = 0;
std::string tempQuestion = question;
while (tempQuestion.find(q) != std::string::npos) {
score++;
tempQuestion = tempQuestion.substr(tempQuestion.find(q) + q.length());
}
if (score > bestMatchScore) {
bestMatch = q;
bestMatchScore = score;
}
}
return bestMatch;
}
std::vector<std::string> splitSentences(const std::string& input) {
std::vector<std::string> sentences;
size_t startPos = 0;
while (startPos < input.length()) {
size_t endPos = input.find_first_of(".,,。", startPos);
if (endPos == std::string::npos) {
sentences.push_back(trim(input.substr(startPos)));
break;
}
sentences.push_back(trim(input.substr(startPos, endPos - startPos + 1)));
startPos = endPos + 1;
}
return sentences;
}
int main() {
// 读取配置文件
std::ifstream configFile("config.ini");
std::vector<std::string> questions;
std::vector<std::string> answers;
std::string line;
while (std::getline(configFile, line)) {
size_t pos = line.find("=");
if (pos != std::string::npos) {
std::string question = trim(line.substr(0, pos));
std::string answer = trim(line.substr(pos + 1));
if (!question.empty() && !answer.empty()) {
questions.push_back(question);
answers.push_back(answer);
}
}
}
configFile.close();
// 开始对话
std::string userInput;
std::cout << "你好!有什么问题可以帮你解答?(输入 q 退出)" << std::endl;
while (true) {
std::cout << "> ";
std::getline(std::cin, userInput);
if (userInput == "q" || userInput == "Q") {
break;
}
std::vector<std::string> sentences = splitSentences(userInput);
for (const std::string& sentence : sentences) {
std::string bestMatch = findBestMatch(sentence, questions);
if (!bestMatch.empty()) {
int index = std::find(questions.begin(), questions.end(), bestMatch) - questions.begin();
std::cout << "- " << answers[index] << std::endl;
} else {
std::cout << "- 对不起,我不懂您的问题。" << std::endl;
}
}
}
return 0;
}
请注意,以上代码仅为简单示例,使用了简单的字符串匹配方式来寻找最佳匹配问题。实际应用中,可能需要使用更复杂的算法,如自然语言处理 (NLP) 技术来改进匹配准确性。
此外,config.ini 文件应包含问题和对应的回答,格式如下:
问题1=回答1
问题2=回答2
...
注意:config.ini 文件路径应与程序运行路径保持一致。
原文地址: https://www.cveoy.top/t/topic/nDw 著作权归作者所有。请勿转载和采集!