Бот b4 ИИ на С плюс
#include <fstream>
#include <string>
#include <vector>
#include <set>
#include <algorithm>
#include <random>
void save_line_number(const std::string& filename, int line_number, const std::set<std::string>& matched_word) {
std::ofstream lines_file(filename, std::ios::app);
for (const auto& word : matched_word) {
lines_file << line_number << " " << word << "\n";
}
}
int main() {
std::string filename = "фразы.txt";
std::string lines_filename = "строки.txt";
std::string line, query, word;
std::ifstream file(filename);
std::vector<std::string> lines;
while (getline(file, line)) {
lines.push_back(line);
}
file.close();
std::cout << " строк в базе: " << lines.size() << std::endl;
std::string previous_line = "";
while (true) {
std::ifstream file(filename);
std::string text((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
file.close();
std::cout << "Вы: ";
std::cin >> query;
std::transform(query.begin(), query.end(), query.begin(), ::tolower);
std::set<std::string> duplicates;
std::istringstream iss(query);
while (iss >> word) {
if (word.length() > 4) {
word = word.substr(0, 5);
}
duplicates.insert(word);
}
std::vector<std::tuple<std::string, int, int>> matching_lines;
int line_number = 0;
std::istringstream text_stream(text);
while (getline(text_stream, line)) {
int count = 0;
std::istringstream line_stream(line);
while (line_stream >> word) {
if (word.length() > 4) {
word = word.substr(0, 5);
}
if (duplicates.find(word) != duplicates.end()) {
count++;
}
}
if (count > 0) {
matching_lines.push_back(std::make_tuple(line, count, line_number));
}
line_number++;
}
if (!matching_lines.empty()) {
std::sort(matching_lines.begin(), matching_lines.end(), [](const auto& a, const auto& b {
return std::get<1>(a) > std::get<1>(b);
});
matching_lines.resize(50);
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, matching_lines.size() - 1);
auto chosen = matching_lines[dis(gen)];
if (std::get<0>(chosen) != previous_line) {
std::cout << "Бот: " << std::get<0>(chosen) << std::endl;
} else {
std::cout << "> " << std::get<0>(matching_lines[1]) << std::endl;
}
previous_line = std::get<0>(chosen);
std::set<std::string> matched_word;
std::istringstream chosen_line_stream(std::get<0>(chosen));
while (chosen_line_stream >> word) {
if (duplicates.find(word) != duplicates.end()) {
matched_word.insert(word);
}
}
save_line_number(lines_filename, std::get<2>(chosen), matched_word);
std::ofstream out_file(filename, std::ios::app);
out_file << "\n" << query;
}
}
return 0;
}
Свидетельство о публикации №124051500336