Home > other >  I need to search a string for patterns from a list
I need to search a string for patterns from a list

Time:02-17

Basically I have a list and I want to search a string for any pattern within it that also follows the list.

    KB1 = ["q","w","e","r","t","y","u","i","o","p"]

    Example = ("yada yada qwe tYu IoP weR")

and for every time it finds qwe ,tYu ,IoP and weR I just need it to add one to a variable, and as shown above needs to also find them regardless of capitalization.

    TimesPatternsAppear = 0

Any ideas?

CodePudding user response:

You could concatenate the individual letters from the list to a string and then simply use the in or find operators to see if one string is found inside the other (as is done here). And if you apply the .lower() method to both strings (or, alternatively, .upper(), but it must be the same for both strings), it will be case-insensitive.

CodePudding user response:

How about this?

KB1 = ["q","w","e","r","t","y","u","i","o","p"]
Example = "yada yada qwe tYu IoP weR"

string_as_a_list = Example.split(" ")
TimesPatternsAppear=0
for eachWord in string_as_a_list:
    eachWord = eachWord.lower()  
    counter = 0
    for char in eachWord:
        if char in KB1:
            counter  =1
        if counter == len(eachWord):
            TimesPatternsAppear  =1
print(TimesPatternsAppear)

CodePudding user response:

Another approach would be to create a list containing the different possible combinations:

KB1 = ["q","w","e","r","t","y","u","i","o","p"]
Example = ("yada yada qwe tYu IoP weR")
TimesPatternsAppear = 0

patterns = []
for i in range(len(KB1)):
    for j in range(i   1, len(KB1)):
        patterns.append("".join(KB1[i:j]))
for word in Example.split():
    if word.lower() in patterns:
        TimesPatternsAppear  = 1
print(TimesPatternsAppear)
  • Related