【发布时间】:2019-05-11 14:45:05
【问题描述】:
我需要解析聊天机器人服务器返回的文本,看看它是否包含特定的单词或 2-3 个单词的短语。
我将这些特定的单词或短语称为键,总共最多有 20 -30 个。
最有效的方法是什么?
如果我只搜索 20-30 个单词-短语是“if-else”逻辑流程,还是有更好的方法?
【问题讨论】:
我需要解析聊天机器人服务器返回的文本,看看它是否包含特定的单词或 2-3 个单词的短语。
我将这些特定的单词或短语称为键,总共最多有 20 -30 个。
最有效的方法是什么?
如果我只搜索 20-30 个单词-短语是“if-else”逻辑流程,还是有更好的方法?
【问题讨论】:
使用 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 - 那么您至少找到了 1 个字符串。
示例程序:
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
}
【讨论】: