Search code examples
pythonpython-2.7textnltk

Tokenize words in a list of sentences Python


i currently have a file that contains a list that is looks like

example = ['Mary had a little lamb' , 
           'Jack went up the hill' , 
           'Jill followed suit' ,    
           'i woke up suddenly' ,
           'it was a really bad dream...']

"example" is a list of such sentences , and i want the output to look as :

mod_example = ["'Mary' 'had' 'a' 'little' 'lamb'" , 'Jack' 'went' 'up' 'the' 'hill' ....] and so on. I need the sentences to be separate with each word tokenized so that i can compare each word from a sentence of mod_example (at a time using for loop) with a reference sentence.

I tried this :

for sentence in example:
    text3 = sentence.split()
    print text3 

and got the follwing as output :

['it', 'was', 'a', 'really', 'bad', 'dream...']

How do I get this for all the sentences? it keeps overwriting . and yes , also mention whether my approach is right? this should remain a list of sentences with the words tokenized.. thanks


Solution

  • You could use the word tokenizer in NLTK (http://nltk.org/api/nltk.tokenize.html) with a list comprehension, see http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions

    >>> from nltk.tokenize import word_tokenize
    >>> example = ['Mary had a little lamb' , 
    ...            'Jack went up the hill' , 
    ...            'Jill followed suit' ,    
    ...            'i woke up suddenly' ,
    ...            'it was a really bad dream...']
    >>> tokenized_sents = [word_tokenize(i) for i in example]
    >>> for i in tokenized_sents:
    ...     print i
    ... 
    ['Mary', 'had', 'a', 'little', 'lamb']
    ['Jack', 'went', 'up', 'the', 'hill']
    ['Jill', 'followed', 'suit']
    ['i', 'woke', 'up', 'suddenly']
    ['it', 'was', 'a', 'really', 'bad', 'dream', '...']