我耗时5天,完成了一个简单的人工智能代码
上代码
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cctype>
using namespace std;
string preprocessInput(const string& input) {
string processed;
for (char c : input) {
if (isalpha(c)) {
processed += tolower(c);
} else if (isspace(c)) {
processed += ' ';
}
}
return processed;
}
bool containsKeyword(const string& input, const vector<string>& keywords) {
string processed = preprocessInput(input);
for (const string& keyword : keywords) {
if (processed.find(keyword) != string::npos) {
return true;
}
}
return false;
}
string getAIResponse(const string& userInput) {
vector<string> greetings = {"hello", "hi", "hey"};
vector<string> farewells = {"bye", "goodbye", "see you"};
vector<string> questions = {"what", "how", "why", "when", "where", "who"};
vector<string> thanks = {"thank", "thanks", "appreciate"};
string processed = preprocessInput(userInput);
if (containsKeyword(userInput, greetings)) {
vector<string> responses = {
"Hello!", "Hi there!", "Hey!", "Greetings!"
};
return responses[rand() % responses.size()];
}
else if (containsKeyword(userInput, farewells)) {
vector<string> responses = {
"Goodbye!", "See you later!", "Bye!", "Until next time!"
};
return responses[rand() % responses.size()];
}
else if (containsKeyword(userInput, questions)) {
return "That's an interesting question. I'm still learning, so I might not have all the answers.";
}
else if (containsKeyword(userInput, thanks)) {
vector<string> responses = {
"You're welcome!", "No problem!", "Happy to help!", "Anytime!"
};
return responses[rand() % responses.size()];
}
else if (processed.find("name") != string::npos) {
return "I'm just a simple AI program. You can call me AI.";
}
else if (processed.find("age") != string::npos) {
return "I don't have an age in the traditional sense. I was created in 2025,by MAX.";
}
else if (processed.find("weather") != string::npos) {
return "I'm sorry, I can't access real-time weather data. You might want to check a google weather app.";
}
else {
vector<string> defaultResponses = {
"Interesting point.", "Tell me more about that.", "I see.",
"That's fascinating.", "I'm not sure I understand completely.",
"Could you clarify that?", "What do you think about that?"
};
return defaultResponses[rand() % defaultResponses.size()];
}
}
int main() {
cout << "AI: Hello! How can I help you today? (Type 'quit' to exit)" << endl;
string userInput;
while (true) {
cout << " "x":";
getline(cin, userInput);
string processed = preprocessInput(userInput);
if (processed.find("quit") != string::npos ||
processed.find("exit") != string::npos ||
processed.find("bye") != string::npos) {
cout << "AI: Goodbye! Have a great day!" << endl;
break;
}
string response = getAIResponse(userInput);
cout << "AI: " << response << endl;
}
return 0;
}
最后,还是感谢你看到最后,关注一下我吧| |
\/