Home > Mobile >  How to check whether single and multiple words exist in string?
How to check whether single and multiple words exist in string?

Time:10-13

I need to check wether a WORD (not just any string) exists in a sentence. For example "or" in the string "these are words" would return False, whilst "are" would return True.

When checking for a single word its easy. Split the sentance string into a list, and check for desired word in list.

def word_search(word):
    string_split = string.split()
    if word in string_split:
        print("The word is in the list!")
    else:
        print("The word is not in the list!")

This works perfectly well for single words. Problem is if I want to check for example "these are" in the string "these are words" (as long as one of the words given exists in the string the output should be True). When splitting the string into a list, I can only check for one word at a time, and splitting the word/s I want to check causes issues with checking a single word.

I'd rather not use RegEx and keep it to "vanilla" python, but I'm struggling here.

CodePudding user response:

You could try using the intersection method on sets....

target_words = ['hi', 'there']
target = 'hi there friend'
if len(set(target.split()).intersection(target_words)) > 0:
    print('at least one target word found')
else:
    print('none of the target words found')

CodePudding user response:

Would this work;

import itertools
word = "these are"
string = "these are words"
string_split = string.split()

for L in range(len(string_split)   1):
    for subset in itertools.combinations(string_split, L):
        if word == " ".join(subset):
            print("The word is in the list!")

CodePudding user response:

I think this might be what you are after:

def word_search(string, words):
    for word in words.split():
        if word in string:
            return True
    return False

CodePudding user response:

you could use the any() function like so:

searchQueries = ["these", "are", "words"]

if any(query in string for query in searchQueries):
    print("The word is in the list!")

CodePudding user response:

def word_search(word, string):
    string_split = string.split()
    if any(x in word for x in string_split):
        print("The word is in the list!")
    else:
        print("The word is not in the list!")
  • Related