How to iterate through a list of strings (i.e a sentence) and check if it has a specific word in it?

Viewed 121

So the question was to create a function which takes a list of documents (each document is a string) and a keyword. It should return a list of the index values into the original list for all documents containing the keyword.

Example (the result should be [0]):

doc_list = ["The Learn Python Challenge Casino.", "They bought a car", "Casinoville"]
word_search(doc_list, 'casino')

I tried list comprehensions and I don't know where it went wrong. Here's my code:

def word_search(doc_list, keyword):
    indices=[]
    for i, doc in enumerate(doc_list):
        indices =[i for word in doc.split(" ") if word.lower().strip(".,")== keyword.lower()]
        return indices
5 Answers

Your working code :

def word_search(doc_list, keyword):
    indices=[]
    for i, doc in enumerate(doc_list):
        if len([i for word in doc.split() if word.lower().strip(".,")== keyword.lower()])>0:
            indices.append(i)
    return indices

Alternative regex code for your purpose

import re
def word_search_re(doc_list, keyword):
    indices=[]
    keyword='\\b'+keyword+'\\b'
    for i, doc in enumerate(doc_list):
        doc=re.sub('(\.|,)+',"",doc)
        if re.search(keyword,doc,re.IGNORECASE):
            indices.append(i)
    return indices

In each iteration, you override the value of indices + the return statement is in the wrong place so it actually always returns after checking the first sentence.

def word_search(doc_list, keyword):
    indices=[]
    for i, doc in enumerate(doc_list):
        sentence_words = [word.strip(".,")for word in doc.lower().split(" ")]
        if keyword in sentence_words:
            indices.append(i)
    return indices
doc_list = ["The Learn Python Challenge Casino.", "They bought a car", "Casinoville"]
    
def word_search(doc_list, keyword):
  values = []
  for key,value in enumerate(doc_list):
    sentence_words = [word.strip(".,")for word in value.lower().split(" ")]
    if keyword in sentence_words:
      values.append(key)
  return values
print(word_search(doc_list,"casino"))

This will give you the indices that matched on each item of doc_list as well as cater for case sensitivity:

def word_search(word_list, search):
    search = search.lower()
    def trim_and_lower(s):
        return s.split(".")[0].lower()

    # normalize string
    str_list = map(trim_and_lower, doc_list)
    indices = [[i for i, c in enumerate(ln.split(" ")) if c == search] for ln in str_list]
    return list(indices)

Your code as a list comprehension one liner:

def word_search(doc_list, keyword):
    return [i for i, doc in enumerate(doc_list) if any(keyword.lower() == w.lower().strip(".,") for w in doc.split(" "))]
    

Here's an almost-one-liner, which is still readable, using map. A true one-liner is non maintainable in this case.

doc_list = ["The Learn Python Challenge Casino.", "They bought a car", "Casinoville"]
def word_search(doc_list, keyword):
    def find_in_doc(doc: str):
        return any(keyword.lower() == w.lower().strip(".,") for w in doc.split(" "))

    return [i for i, v in enumerate(map(find_in_doc, doc_list)) if v]

print(word_search(doc_list, "casino"))

[0]

Related