我需要分析由聊天机器人服务器返回的文本,看看它是否包含特定的单词或2-3个单词的短语。
这些特定的单词或短语我称为关键,最多只能有20 -30个。
实现这一目标的最有效方法是什么?
如果我只搜索20-30个单词--短语是一个' If -else‘逻辑流程是可以的,还是有更好的方法?
发布于 2019-05-12 00:53:13
使用LINQ -将你想要检查的所有单词放在一个List<string>
中,然后从聊天机器人中获取文本,并使用list.Any(x=>chatBotString.IndexOf(x) > -1)
-假设你ToLower()
和Trim()
所有的东西,这应该可以工作。
假设聊天机器人字符串s
为"the red fox jumped over the brown dog under the fence, I don't actually know what the sentence is"
,术语列表L
为
"red fox"
"brown dog"
"under the fence"
"actually know"
你做了
L.Any(x=>s.Trim().ToLower().IndexOf(x.Trim().ToLower())>-1)
如果你得到true
-,那么你至少找到了一个字符串。
示例程序:
void Main()
{
var l = new List<string> {
"red fox",
"brown dog",
"under the fence",
"actually know"
};
var s = "the red fox jumped over the brown dog under the fence, I don't actually know what the sentence is";
s = s.Trim().ToLower();
l.Any(x => s.IndexOf(x.Trim().ToLower()) > -1); // true
s = "this is a sentence with no matches";
s = s.Trim().ToLower();
l.Any(x => s.IndexOf(x.Trim().ToLower()) > -1); // false
}
https://stackoverflow.com/questions/56091373
复制相似问题