In this tutorial, we will introduce how to tokenize text sentences and words using python nltk library.
1. Import library
from nltk.tokenize import sent_tokenize, word_tokenize
2. Create a text to tokenize
text = "Natural language processing (NLP) is a field " + \ "of computer science, artificial intelligence " + \ "and computational linguistics concerned with " + \ "the interactions between computers and human " + \ "(natural) languages, and, in particular, " + \ "concerned with programming computers to " + \ "fruitfully process large natural language " + \ "corpora. Challenges in natural language " + \ "processing frequently involve natural " + \ "language understanding, natural language" + \ "generation frequently from formal, machine" + \ "-readable logical forms), connecting language " + \ "and machine perception, managing human-" + \ "computer dialog systems, or some combination " + \ "thereof."
In this text, there are some sentences and each sentence contains some words, we will tokenize them.
4. Tokenize sentences
sen_tokens = sent_tokenize(text) print(len(sen_tokens)) print(sen_tokens)
Then you will get the result:
2 ['Natural language processing (NLP) is a field of computer science, artificial intelligence and computational linguistics concerned with the interactions between computers and human (natural) languages, and, in particular, concerned with programming computers to fruitfully process large natural language corpora.', 'Challenges in natural language processing frequently involve natural language understanding, natural languagegeneration frequently from formal, machine-readable logical forms), connecting language and machine perception, managing human-computer dialog systems, or some combination thereof.']
Which means there are 2 sentences in text.
5. Tokenize words
word_tokens = word_tokenize(text) print(len(word_tokens)) print(word_tokens)
Run this code, you will get:
86 ['Natural', 'language', 'processing', '(', 'NLP', ')', 'is', 'a', 'field', 'of', 'computer', 'science', ',', 'artificial', 'intelligence', 'and', 'computational', 'linguistics', 'concerned', 'with', 'the', 'interactions', 'between', 'computers', 'and', 'human', '(', 'natural', ')', 'languages', ',', 'and', ',', 'in', 'particular', ',', 'concerned', 'with', 'programming', 'computers', 'to', 'fruitfully', 'process', 'large', 'natural', 'language', 'corpora', '.', 'Challenges', 'in', 'natural', 'language', 'processing', 'frequently', 'involve', 'natural', 'language', 'understanding', ',', 'natural', 'languagegeneration', 'frequently', 'from', 'formal', ',', 'machine-readable', 'logical', 'forms', ')', ',', 'connecting', 'language', 'and', 'machine', 'perception', ',', 'managing', 'human-computer', 'dialog', 'systems', ',', 'or', 'some', 'combination', 'thereof', '.']
Which means there are 86 words in text.