Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract each word from list of strings

Tags:

python

I am using Python my list is

str = ["Hello dude", "What is your name", "My name is Chetan"]

I want to separate each word in each sentence in the string and store it in new_list. new_list will be like

new_list = ["Hello", "dude", "What", "is", "your", "name", "My", "name", 
            "is", "Chetan"]

I tried with the code

for row in str:
    new_list.append(row.split(" "))

Output:

[['Hello', 'dude'], ['What', 'is', 'your', 'name'], ['My', 'name', 'is', 
  'Chetan']]

which is list of list

like image 465
Chetan Tamboli Avatar asked Jan 03 '23 17:01

Chetan Tamboli


2 Answers

You could use itertools.chain

from itertools import chain

def split_list_of_words(list_):
    return list(chain.from_iterable(map(str.split, list_)))

DEMO

input_ = [
          "Hello dude", 
          "What is your name", 
          "My name is Chetan"
         ]

result = split_list_of_words(input_)

print(result)
#['Hello', 'dude', 'What', 'is', 'your', 'name', 'My', 'name', 'is', 'Chetan']
like image 66
Abdul Niyas P M Avatar answered Jan 05 '23 06:01

Abdul Niyas P M


you have,

values = ["Hello dude", "What is your name", "My name is Chetan"]

then use this one liner

' '.join(values).split()
like image 37
Haseeb A Avatar answered Jan 05 '23 05:01

Haseeb A