Search code examples
stringlistappenduniquematching

To get only First matching word only from each string from a list of string?


list_of_string = ["Mumbai Mumbai USA", "Country India America", "Delhi Mumbai USA", "Mumbai India"]
words = ["mumbai", "america", "usa", "delhi","india"]
match = []
def match_words(text, search):
    lower = [x.lower() for x in text]
    f_text = [y for lines in lower for y in lines.split()]
    for text_word in f_text:
        for search_word in search:
            if search_word == text_word:
                if search_word not in match:
                    match.append(search_word) 

`

#calling the function

match_words(list_of_string, words)

I want this output: ["mumbai", "india","delhi","mumbai"] I'm getting this output: ["mumbai","usa","india","america","delhi"]


Solution

  • Try this...

    list_of_string = ["Mumbai Mumbai USA", "Country India America", "Delhi Mumbai USA", "Mumbai India"]
    words = ["mumbai", "america", "usa", "delhi","india"]
    match = []
    
    def match_words(text, search):
        lower = [x.lower() for x in text]
    
        for temp in lower:
            f_text = temp.split()
            found = False
            for text_word in f_text:
                for search_word in search:
                    if search_word == text_word:
                        match.append(search_word)
                        found = True
                        break
    
                if (found): break
    
    
    
    match_words(list_of_string, words)
    print(match);