简体   繁体   中英

Parse returned text for specific set of words or phrases

I need to parse text returned by a chatbot server and see if it contains a specific word or 2-3 word phrase.

These specific words or phrases I refer to as keys and will have at most about 20 -30 total.

What would be the most efficient way to accomplish this?

If I am searching only for 20-30 words-phrases is an 'if-else' logic flow ok or is there a better way?

use LINQ - put all the words you want check for in a List<string> , then get the text from the chat bot, and list.Any(x=>chatBotString.IndexOf(x) > -1) - assuming you ToLower() and Trim() everything, this should work.

Let's say your chat bot string s is "the red fox jumped over the brown dog under the fence, I don't actually know what the sentence is" and your list of terms L is

"red fox"
"brown dog"
"under the fence"
"actually know"

you do

L.Any(x=>s.Trim().ToLower().IndexOf(x.Trim().ToLower())>-1)

If you get true - then you found at least 1 string.

Sample program:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM