C++ 实现聊天机器人 - 自动匹配语料库问题
#include
// 根据分隔符将字符串分割为多个子字符串 std::vectorstd::string split(const std::string& str, char delimiter) { std::vectorstd::string tokens; std::stringstream ss(str); std::string token; while (std::getline(ss, token, delimiter)) { tokens.push_back(token); } return tokens; }
// 将字符串转换为小写 std::string toLower(const std::string& str) { std::string result = str; std::transform(result.begin(), result.end(), result.begin(), ::tolower); return result; }
// 加载语料库 std::map<std::string, std::string> loadCorpus(const std::string& filename) { std::map<std::string, std::string> corpus; std::ifstream file(filename); std::string line; while (std::getline(file, line)) { std::vectorstd::string parts = split(line, '='); if (parts.size() == 2) { std::string question = toLower(parts[0]); std::string answer = parts[1]; corpus[question] = answer; } } return corpus; }
// 计算字符串的相似度
int calculateSimilarity(const std::string& str1, const std::string& str2) {
int n = str1.length();
int m = str2.length();
std::vector<std::vector
for (int i = 1; i <= n; i++) {
dp[i][0] = i;
}
for (int j = 1; j <= m; j++) {
dp[0][j] = j;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (str1[i - 1] == str2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
}
else {
dp[i][j] = std::min({ dp[i - 1][j - 1] + 1, dp[i][j - 1] + 1, dp[i - 1][j] + 1 });
}
}
}
return dp[n][m];
}
// 查找与问题匹配程度最高的问题 std::string findBestMatch(const std::map<std::string, std::string>& corpus, const std::string& question) { int minSimilarity = INT_MAX; std::string bestMatch; for (const auto& entry : corpus) { int similarity = calculateSimilarity(question, entry.first); if (similarity < minSimilarity) { minSimilarity = similarity; bestMatch = entry.first; } } return bestMatch; }
// 获取回答 std::string getAnswer(const std::map<std::string, std::string>& corpus, const std::string& question) { std::string lowerQuestion = toLower(question); std::string bestMatch = findBestMatch(corpus, lowerQuestion); return corpus.at(bestMatch); }
int main() { std::map<std::string, std::string> corpus = loadCorpus("config.ini");
std::string input;
std::cout << "请输入问题:";
std::getline(std::cin, input);
std::vector<std::string> sentences = split(input, '.');
std::vector<std::string> sentences2 = split(input, ',');
std::vector<std::string> sentences3 = split(input, ',');
for (const auto& sentence : sentences) {
std::string answer = getAnswer(corpus, sentence);
std::cout << "回答:" << answer << std::endl;
}
for (const auto& sentence : sentences2) {
std::string answer = getAnswer(corpus, sentence);
std::cout << "回答:" << answer << std::endl;
}
for (const auto& sentence : sentences3) {
std::string answer = getAnswer(corpus, sentence);
std::cout << "回答:" << answer << std::endl;
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/jLe 著作权归作者所有。请勿转载和采集!