【问题标题】:Parse returned text for specific set of words or phrases为特定的单词或短语集解析返回的文本
【发布时间】:2019-05-11 14:45:05
【问题描述】:

我需要解析聊天机器人服务器返回的文本,看看它是否包含特定的单词或 2-3 个单词的短语。

我将这些特定的单词或短语称为键,总共最多有 20 -30 个。

最有效的方法是什么?

如果我只搜索 20-30 个单词-短语是“if-else”逻辑流程,还是有更好的方法?

【问题讨论】:

    标签: c# parsing


    【解决方案1】:

    使用 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
    }
    

    【讨论】:

    • 谢谢!!需要阅读更多关于 LINQ 的信息。有人建议使用带代表的字典,但这是一个更好的解决方案。
    • 意识到我不需要找到任何匹配,而是特定匹配,因此包含扩展方法可能对我更好。
    猜你喜欢
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    相关资源
    最近更新 更多