【问题标题】:Finding keyword in strings c++在字符串c ++中查找关键字
【发布时间】:2019-02-27 21:20:33
【问题描述】:

我对 C++ 和编程还很陌生,所以我可能只是在这里遗漏了一些重要的东西。

我正在尝试为图书馆创建一个聊天机器人,处理开放时间等问题。我希望聊天机器人能够在输入中提取关键词,然后能够调用能够将一些文本返回给它们的正确函数。

例如:

用户:图书馆开到几点? //chatbot 获取关键字'open'并返回正确的函数 聊天机器人:图书馆在 6 点到 5 点之间开放

让聊天机器人执行此操作应该不会像我发现的那么难。

我遇到问题的函数:

std::string GetKeywords(){
std::string KQuery = GetQuery();


std::vector<std::string> keywords{"open", "opening", "times", "close", "closing", "shut"};


    if(std::find(keywords.begin(), keywords.end(), KQuery) != keywords.end()){
        std::cout << "Library is open when I say it is" << std::endl;
    }
return 0;
};

这将返回一个内存错误,并且是我的代码中唯一引发问题的地方。

我所有的代码:

#include <iostream>
#include <string>
#include <vector>

#include "FinalProject.hpp"

//introducing funtions
void PrintIntro();
std::string GetQuery();
std::string RunScripts();
std::string GetKeywords();;

// introducing chatbot
RunScript ChatBot;


int main(){

PrintIntro();
GetQuery();
GetKeywords();

};



void PrintIntro(){
    //printing introductory text to ask the user for input
std::cout << "Hi, I'm Librarius, I'm here to help you with University     library queries" << std::endl;
std::cout << "I can help you with the following: \n Spaces to study \n     Opening times \n Taking out books \n Returning books\n" << std:: endl;
std::cout << "Ask away!" << std::endl;
return;
};



std::string GetQuery(){
//getting input from the user
std::string Query = "";
std::getline(std::cin, Query);

if(Query.empty()){
    //checking to see if the user hasnt entered anything
    std::cout << "Hey! Why didnt you enter anything?! I don't want to waste my time!" << std::endl;
};

return Query;
};

std::string GetKeywords(){
std::string KQuery = GetQuery();


std::vector<std::string> keywords{"open", "opening", "times", "close", "closing", "shut"};


    if(std::find(keywords.begin(), keywords.end(), KQuery) != keywords.end()){
        std::cout << "Library is open when I say it is" << std::endl;
    }



return 0;
};

//using the input got from the user to decide which script to run

//TODO analyse the users keywords and decide on a script to run

//TODO return an appropriate script

感谢您的帮助!

【问题讨论】:

  • 并非所有代码:..\main.cpp:5:10: fatal error: FinalProject.hpp: No such file or directory。实际上,我们宁愿拥有minimal reproducible example,也不愿拥有您的所有代码。

标签: c++ vector nlp chatbot


【解决方案1】:

问题

std::find(keywords.begin(), keywords.end(), KQuery)

它会查看KQuery 中的整个字符串是否与您的关键字之一匹配。由于KQuery 中有一个句子,它不会找到匹配项。您需要做的是遍历所有关键字并查看KQuery.find(keyword) 是否返回有效结果。

您可以使用 std::find_if 和类似的 lambda 来做到这一点

std::find_if(keywords.begin(), keywords.end(),
             [&](auto const& keyword){ return KQuery.find(keyword) != std::string::npos; });

如果没有找到任何关键字,这将返回一个迭代器,指向它在KQuerykeywords.end() 中找到的第一个关键字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-15
    • 2012-11-10
    • 1970-01-01
    相关资源
    最近更新 更多