Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python convert list of multiple words to single words

Tags:

python

nlp

nltk

I have a list of words for example:

words = ['one','two','three four','five','six seven'] # quote was missing

And I am trying to create a new list where each item in the list is just one word so I would have:

words = ['one','two','three','four','five','six','seven']

Would the best thing to do be join the entire list into a string and then tokenize the string? Something like this:

word_string = ' '.join(words) tokenize_list = nltk.tokenize(word_string)

Or is there a better option?

like image 655
GNMO11 Avatar asked Nov 30 '22 00:11

GNMO11


2 Answers

words = ['one','two','three four','five','six seven']

With a loop:

words_result = []
for item in words:
    for word in item.split():
        words_result.append(word)

or as a comprehension:

words = [word for item in words for word in item.split()]
like image 72
TigerhawkT3 Avatar answered Dec 05 '22 12:12

TigerhawkT3


You can join using a space separator and then split again:

In [22]:

words = ['one','two','three four','five','six seven']
' '.join(words).split()
Out[22]:
['one', 'two', 'three', 'four', 'five', 'six', 'seven']
like image 39
EdChum Avatar answered Dec 05 '22 13:12

EdChum