Search code examples
pythonnumpynlpstemming

How to replace word in array of text in Python?


I want to stem my text with my own array:

word_list1 = ["cccc", "bbbb", "aaa"]

def stem_text(text):
     text = text.split()
     array = np.array(text)
     temp = np.where(array == word_list1, word_list1[0], array)
     text = ' '.join(temp)
     return text

I want to do like this:

for all of the word in word_list1, check the text and if some word matched, replace it with word_list[0]


Solution

  • You can use list comprehension

    word_list1 = ["cccc", "bbbb", "aaa"]
    
    def stem_text(text):
        text = text.split()
        temp = [word_list1[0] if i in word_list1 else i for i in text]
        text = ' '.join(temp)
        return text
    
    stem_text("hello bbbb now aaa den kkk")
    

    Output :

    'hello cccc now cccc den kkk'