Python – Word Tokenization

Python – Word Tokenization

Python – Word Tokenization

Word tokenization is the process of splitting a large sample of text into words. This is a requirement in natural language processing tasks where each word needs to be captured and subjected
to further analysis like classifying and counting them for a particular sentiment etc. The Natural Language Tool kit(NLTK) is a library used to achieve this. Install NLTK before proceeding with the python
program for word tokenization.

conda install -c anaconda nltk

Next we use the word_tokenize method to split the paragraph into individual words.

import nltk
data = "Capitalism is better than communism"
nltk_tokens = nltk.word_tokenize(word_data)
print (nltk_tokens)

When we execute the above code, it produces the following result.

['Capitalism', 'is', 'better', 'than', 'communism']

Tokenizing Sentences

We can also tokenize the sentences in a paragraph like we tokenized the words. We use the method sent_tokenize to achieve this. Below is an example.

import nltk
sentence_data = "Their were nine planets in our solar system.But as pluto was removed from the list so now their are eight."
nltk_tokens = nltk.sent_tokenize(sentence_data)
print (nltk_tokens)

When we execute the above code, it produces the following result.

['Their were nine planets in our solar system.', '.But as pluto was removed from the list so now their are eight.']
Python – Processing Unstructured Data (Prev Lesson)
(Next Lesson) Python – Chart Styling