We start with four sentences:
there is a dog in the garden
john enjoys watching movies
jane enjoys taking her dog for a walk
there are no dogs in this movie
Computers don't handle natural language well. One way to overcome this is to create a 'bag of words'
for each sentence. This can be thought of as a list of integer values. Each value is the number of occurences
of a word in the sentence.
The first step is to tokenize the sentences then to create a set from this list of tokens. We can then
itterate through each word in the set and count the number of times that word occurs in each sentence.
The number is appended to a list. This process generates three lists or vectors.
list_of_sentences = ['there is a dog in the garden','john enjoys watching movies','jane enjoys taking her dog for a walk','there are no dogs in this movie']
text = 'there is a dog in the garden john enjoys watching movies jane enjoys taking her dog for a walk there are no dogs in this movie'
tokens = nltk.word_tokenize(text)
set_of_words = set(tokens)
sent_1 = 
sent_2 = 
sent_3 = 
for i in range(1,4,1):
sentence = list_of_sentences[i-1]
sent_tokens = nltk.word_tokenize(sentence)
for word in set_of_words:
word_freq = sent_tokens.count(word)
if i == 1:
elif i == 2:
The output is:
[1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0]
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1]
[1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1]
the word set is:
set(['a', 'dogs', 'no', 'garden', 'her', 'watching', 'this', 'movie', 'is',
'there', 'dog', 'for', 'walk', 'movies', 'are', 'in', 'jane', 'taking', 'the',
so 'a' occurs once in the first sentence, 'dogs' does not occur, 'no' does not occur
and so on.
The bag of words approach can be used in computer vision for image recognition/classification.
There are a number of packages that offer 'bag of words' functionality, the above script is not
intended to replace these packages, it is just to demonstrate what is meant by 'bag of words'
This blog includes:
Scripts mainly in Python with a few in R covering NLP, Pandas, Matplotlib and others. See the home page for links to some of the scripts. Also includes some explanations of basic data science terminology.