BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

NLTK (Natural Language Toolkit) tokenization and tagging

NLTK_LOGO.png




Bookmark and Share





bogotobogo.com site search:






NLTK Tutorials

Introduction - Install NLTK

Tokenizing and Tagging

Stemming

Chunking

tf-idf

tokenization and tagging

NLTK provides support for a wide variety of text processing tasks. In this section, we'll do tokenization and tagging.

We're going to use Steinbeck Pearl Ch. 3 as an input.

import nltk
from collections import Counter

def get_tokens():
	with open('/home/k/TEST/NLTK/Pearl3.txt') as pearl:
		tokens = nltk.word_tokenize(pearl.read())
	return tokens

if __name__ == "__main__":

	tokens = get_tokens()
	print("tokens=%s") %(tokens)

	count = Counter(tokens)
	print("len(count) = %s") %(len(count))
	print("most_common = %s") %(count.most_common(10))

	tagged = nltk.pos_tag(tokens)
	print("tagged=%s") %(tagged)

Output:

tokens[:20]=['Chapter', '3', 'A', 'town', 'is', 'a', 'thing', 'like', 'a', 'colonial', 'animal.', 'A', 'town', 'has', 'a', 'nervous', 'system', 'and', 'a', 'head']
len(count) = 1459
most_common = [('the', 429), ('and', 314), (',', 313), ('a', 145), ('of', 138), ('he', 122), ('in', 115), ('his', 110), ('to', 104), ('Kino', 98)]
tagged[:20]=[('Chapter', 'NN'), ('3', 'CD'), ('A', 'DT'), ('town', 'NN'), ('is', 'VBZ'), ('a', 'DT'), ('thing', 'NN'), ('like', 'IN'), ('a', 'DT'), ('colonial', 'JJ'), ('animal.', 'NNP'), ('A', 'DT'), ('town', 'NN'), ('has', 'VBZ'), ('a', 'DT'), ('nervous', 'JJ'), ('system', 'NN'), ('and', 'CC'), ('a', 'DT'), ('head', 'NN')]

As we see from the output for most_common, we have (',', 313). So, if we don't want to process any punctuation, we can use the character deletion step of translate():

import nltk
from collections import Counter
import string

def get_tokens():
	with open('/home/k/TEST/NLTK/Pearl3.txt') as pearl:
		tokens = nltk.word_tokenize(pearl.read().translate(None, string.punctuation))
	return tokens

if __name__ == "__main__":

	tokens = get_tokens()
	print("tokens[:20]=%s") %(tokens[:20])

	count = Counter(tokens)
	print("len(count) = %s") %(len(count))
	print("most_common = %s") %(count.most_common(10))

	tagged = nltk.pos_tag(tokens)
	print("tagged[:20]=%s") %(tagged[:20])

Then, we get an output processed without any punctuation:

tokens[:20]=['Chapter', '3', 'A', 'town', 'is', 'a', 'thing', 'like', 'a', 'colonial', 'animal', 'A', 'town', 'has', 'a', 'nervous', 'system', 'and', 'a', 'head']
len(count) = 1299
most_common = [('the', 429), ('and', 315), ('a', 145), ('of', 138), ('he', 122), ('in', 120), ('his', 110), ('to', 104), ('it', 89), ('was', 84)]
tagged[:20]=[('Chapter', 'NN'), ('3', 'CD'), ('A', 'DT'), ('town', 'NN'), ('is', 'VBZ'), ('a', 'DT'), ('thing', 'NN'), ('like', 'IN'), ('a', 'DT'), ('colonial', 'JJ'), ('animal', 'JJ'), ('A', 'DT'), ('town', 'NN'), ('has', 'VBZ'), ('a', 'DT'), ('nervous', 'JJ'), ('system', 'NN'), ('and', 'CC'), ('a', 'DT'), ('head', 'NN')]

Now the size of the count has been reduced from len(count) = 1459 => len(count) = 1299.


Removing Stop Words I

Sometimes, common words which would appear to be of little value for selecting documents matching are excluded from the vocabulary entirely. These words are called stop words. The general strategy for determining a stop list is to sort the terms by frequency, and then to label the most frequent terms as a stop list. Then, they are discarded during indexing.

The example of the list: a, an, the, he, by, it, are, etc.

Before using the 'stopwords', we need to download the list from nltk, otherwise we may get the error like this:

LookupError: 
**********************************************************************
  Resource 'corpora/stopwords' not found.  Please use the NLTK
  Downloader to obtain the resource: >>> nltk.download().

We may follow the steps after issuing nltk.download() or we can do the following:

>>> import nltk
>>> nltk.download('stopwords')

Now, we can use the list:

>>> from nltk.corpus import stopwords
>>> stopwords.words('english')
['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', 'she', 'her', 'hers', 'herself', 'it', 'its', 'itself', 'they', 'them', 'their', 'theirs', 'themselves', 'what', 'which', 'who', 'whom', 'this', 'that', 'these', 'those', 'am', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', 'did', 'doing', 'a', 'an', 'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', 'at', 'by', 'for', 'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 'after', 'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under', 'again', 'further', 'then', 'once', 'here', 'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more', 'most', 'other', 'some', 'such', 'no', 'nor', 'not', 'only', 'own', 'same', 'so', 'than', 'too', 'very', 's', 't', 'can', 'will', 'just', 'don', 'should', 'now']

Let's incorporate the stopwords into our previous code:

import nltk
from collections import Counter
import string
from nltk.corpus import stopwords

def get_tokens():
	with open('/home/k/TEST/NLTK/Pearl3.txt') as pearl:
		tokens = nltk.word_tokenize(pearl.read().translate(None, string.punctuation))
	return tokens

if __name__ == "__main__":

	tokens = get_tokens()
	print("tokens[:20]=%s") %(tokens[:20])
	
	count = Counter(tokens)
	print("before: len(count) = %s") %(len(count))

	filtered = [w for w in tokens if not w in stopwords.words('english')]

	print("filtered tokens[:20]=%s") %(filtered[:20])
	
	count = Counter(filtered)
	print("after: len(count) = %s") %(len(count))
	
	print("most_common = %s") %(count.most_common(10))

	tagged = nltk.pos_tag(tokens)
	print("tagged[:20]=%s") %(tagged[:20])

Output:

tokens[:20]=['Chapter', '3', 'A', 'town', 'is', 'a', 'thing', 'like', 'a', 'colonial', 'animal', 'A', 'town', 'has', 'a', 'nervous', 'system', 'and', 'a', 'head']
before: len(count) = 1299
filtered tokens[:20]=['Chapter', '3', 'A', 'town', 'thing', 'like', 'colonial', 'animal', 'A', 'town', 'nervous', 'system', 'head', 'shoulders', 'feet', 'A', 'town', 'thing', 'separate', 'towns']
after: len(count) = 1193
most_common = [('Kino', 77), ('And', 58), ('The', 48), ('He', 48), ('pearl', 46), ('little', 45), ('said', 38), ('could', 32), ('Juana', 31), ('Kinos', 29)]
tagged[:20]=[('Chapter', 'NN'), ('3', 'CD'), ('A', 'DT'), ('town', 'NN'), ('thing', 'NN'), ('like', 'IN'), ('colonial', 'JJ'), ('animal', 'JJ'), ('A', 'DT'), ('town', 'NN'), ('nervous', 'JJ'), ('system', 'NN'), ('head', 'NN'), ('shoulders', 'NNS'), ('feet', 'VBP'), ('A', 'DT'), ('town', 'NN'), ('thing', 'NN'), ('separate', 'JJ'), ('towns', 'NNS')]

Notice that the count has been decreases: 1299=>1193!





Removing Stop Words II - lower()

Even though we removed majority of stopwords, we still have some words in the stopwords list such as 'A'. So, we need to lower the case for all the characters of the text before we start process using lower() function.

Here is the final code for this chapter:

import nltk
from collections import Counter
import string
from nltk.corpus import stopwords

def get_tokens():
	with open('/home/k/TEST/NLTK/Pearl3.txt') as pearl:
		tokens = nltk.word_tokenize(pearl.read().lower().translate(None, string.punctuation))
	return tokens

if __name__ == "__main__":

	tokens = get_tokens()
	print("tokens[:20]=%s") %(tokens[:20])
	
	count = Counter(tokens)
	print("before: len(count) = %s") %(len(count))

	filtered = [w for w in tokens if not w in stopwords.words('english')]

	print("filtered tokens[:20]=%s") %(filtered[:20])
	
	count = Counter(filtered)
	print("after: len(count) = %s") %(len(count))
	
	print("most_common = %s") %(count.most_common(10))

	tagged = nltk.pos_tag(filtered)
	print("tagged[:20]=%s") %(tagged[:20])

Output:

tokens[:20]=['chapter', '3', 'a', 'town', 'is', 'a', 'thing', 'like', 'a', 'colonial', 'animal', 'a', 'town', 'has', 'a', 'nervous', 'system', 'and', 'a', 'head']
before: len(count) = 1238
filtered tokens[:20]=['chapter', '3', 'town', 'thing', 'like', 'colonial', 'animal', 'town', 'nervous', 'system', 'head', 'shoulders', 'feet', 'town', 'thing', 'separate', 'towns', 'two', 'towns', 'alike']
after: len(count) = 1131
most_common = [('kino', 77), ('pearl', 50), ('little', 45), ('said', 38), ('could', 32), ('juana', 31), ('kinos', 29), ('doctor', 28), ('eyes', 26), ('came', 26)]
tagged[:20]=[('chapter', 'NN'), ('3', 'CD'), ('town', 'NN'), ('thing', 'NN'), ('like', 'IN'), ('colonial', 'JJ'), ('animal', 'JJ'), ('town', 'NN'), ('nervous', 'JJ'), ('system', 'NN'), ('head', 'NN'), ('shoulders', 'NNS'), ('feet', 'VBP'), ('town', 'VBN'), ('thing', 'NN'), ('separate', 'JJ'), ('towns', 'NNS'), ('two', 'CD'), ('towns', 'NNS'), ('alike', 'IN')]




Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong







Python tutorial



Python Home

Introduction

Running Python Programs (os, sys, import)

Modules and IDLE (Import, Reload, exec)

Object Types - Numbers, Strings, and None

Strings - Escape Sequence, Raw String, and Slicing

Strings - Methods

Formatting Strings - expressions and method calls

Files and os.path

Traversing directories recursively

Subprocess Module

Regular Expressions with Python

Regular Expressions Cheat Sheet

Object Types - Lists

Object Types - Dictionaries and Tuples

Functions def, *args, **kargs

Functions lambda

Built-in Functions

map, filter, and reduce

Decorators

List Comprehension

Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism

Hashing (Hash tables and hashlib)

Dictionary Comprehension with zip

The yield keyword

Generator Functions and Expressions

generator.send() method

Iterators

Classes and Instances (__init__, __call__, etc.)

if__name__ == '__main__'

argparse

Exceptions

@static method vs class method

Private attributes and private methods

bits, bytes, bitstring, and constBitStream

json.dump(s) and json.load(s)

Python Object Serialization - pickle and json

Python Object Serialization - yaml and json

Priority queue and heap queue data structure

Graph data structure

Dijkstra's shortest path algorithm

Prim's spanning tree algorithm

Closure

Functional programming in Python

Remote running a local file using ssh

SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table

SQLite 3 - B. Selecting, updating and deleting data

MongoDB with PyMongo I - Installing MongoDB ...

Python HTTP Web Services - urllib, httplib2

Web scraping with Selenium for checking domain availability

REST API : Http Requests for Humans with Flask

Blog app with Tornado

Multithreading ...

Python Network Programming I - Basic Server / Client : A Basics

Python Network Programming I - Basic Server / Client : B File Transfer

Python Network Programming II - Chat Server / Client

Python Network Programming III - Echo Server using socketserver network framework

Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn

Python Coding Questions I

Python Coding Questions II

Python Coding Questions III

Python Coding Questions IV

Python Coding Questions V

Python Coding Questions VI

Python Coding Questions VII

Python Coding Questions VIII

Python Coding Questions IX

Python Coding Questions X

Image processing with Python image library Pillow

Python and C++ with SIP

PyDev with Eclipse

Matplotlib

Redis with Python

NumPy array basics A

NumPy Matrix and Linear Algebra

Pandas with NumPy and Matplotlib

Celluar Automata

Batch gradient descent algorithm

Longest Common Substring Algorithm

Python Unit Test - TDD using unittest.TestCase class

Simple tool - Google page ranking by keywords

Google App Hello World

Google App webapp2 and WSGI

Uploading Google App Hello World

Python 2 vs Python 3

virtualenv and virtualenvwrapper

Uploading a big file to AWS S3 using boto module

Scheduled stopping and starting an AWS instance

Cloudera CDH5 - Scheduled stopping and starting services

Removing Cloud Files - Rackspace API with curl and subprocess

Checking if a process is running/hanging and stop/run a scheduled task on Windows

Apache Spark 1.3 with PySpark (Spark Python API) Shell

Apache Spark 1.2 Streaming

bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...

Flask app with Apache WSGI on Ubuntu14/CentOS7 ...

Selenium WebDriver

Fabric - streamlining the use of SSH for application deployment

Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App

Neural Networks with backpropagation for XOR using one hidden layer

NLP - NLTK (Natural Language Toolkit) ...

RabbitMQ(Message broker server) and Celery(Task queue) ...

OpenCV3 and Matplotlib ...

Simple tool - Concatenating slides using FFmpeg ...

iPython - Signal Processing with NumPy

iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github

iPython and Jupyter Notebook with Embedded D3.js

Downloading YouTube videos using youtube-dl embedded with Python

Machine Learning : scikit-learn ...

Django 1.6/1.8 Web Framework ...


Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






OpenCV 3 image and video processing with Python



OpenCV 3 with Python

Image - OpenCV BGR : Matplotlib RGB

Basic image operations - pixel access

iPython - Signal Processing with NumPy

Signal Processing with NumPy I - FFT and DFT for sine, square waves, unitpulse, and random signal

Signal Processing with NumPy II - Image Fourier Transform : FFT & DFT

Inverse Fourier Transform of an Image with low pass filter: cv2.idft()

Image Histogram

Video Capture and Switching colorspaces - RGB / HSV

Adaptive Thresholding - Otsu's clustering-based image thresholding

Edge Detection - Sobel and Laplacian Kernels

Canny Edge Detection

Hough Transform - Circles

Watershed Algorithm : Marker-based Segmentation I

Watershed Algorithm : Marker-based Segmentation II

Image noise reduction : Non-local Means denoising algorithm

Image object detection : Face detection using Haar Cascade Classifiers

Image segmentation - Foreground extraction Grabcut algorithm based on graph cuts

Image Reconstruction - Inpainting (Interpolation) - Fast Marching Methods

Video : Mean shift object tracking

Machine Learning : Clustering - K-Means clustering I

Machine Learning : Clustering - K-Means clustering II

Machine Learning : Classification - k-nearest neighbors (k-NN) algorithm




Machine Learning with scikit-learn



scikit-learn installation

scikit-learn : Features and feature extraction - iris dataset

scikit-learn : Machine Learning Quick Preview

scikit-learn : Data Preprocessing I - Missing / Categorical data

scikit-learn : Data Preprocessing II - Partitioning a dataset / Feature scaling / Feature Selection / Regularization

scikit-learn : Data Preprocessing III - Dimensionality reduction vis Sequential feature selection / Assessing feature importance via random forests

Data Compression via Dimensionality Reduction I - Principal component analysis (PCA)

scikit-learn : Data Compression via Dimensionality Reduction II - Linear Discriminant Analysis (LDA)

scikit-learn : Data Compression via Dimensionality Reduction III - Nonlinear mappings via kernel principal component (KPCA) analysis

scikit-learn : Logistic Regression, Overfitting & regularization

scikit-learn : Supervised Learning & Unsupervised Learning - e.g. Unsupervised PCA dimensionality reduction with iris dataset

scikit-learn : Unsupervised_Learning - KMeans clustering with iris dataset

scikit-learn : Linearly Separable Data - Linear Model & (Gaussian) radial basis function kernel (RBF kernel)

scikit-learn : Decision Tree Learning I - Entropy, Gini, and Information Gain

scikit-learn : Decision Tree Learning II - Constructing the Decision Tree

scikit-learn : Random Decision Forests Classification

scikit-learn : Support Vector Machines (SVM)

scikit-learn : Support Vector Machines (SVM) II

Flask with Embedded Machine Learning I : Serializing with pickle and DB setup

Flask with Embedded Machine Learning II : Basic Flask App

Flask with Embedded Machine Learning III : Embedding Classifier

Flask with Embedded Machine Learning IV : Deploy

Flask with Embedded Machine Learning V : Updating the classifier

scikit-learn : Sample of a spam comment filter using SVM - classifying a good one or a bad one




Machine learning algorithms and concepts

Batch gradient descent algorithm

Single Layer Neural Network - Perceptron model on the Iris dataset using Heaviside step activation function

Batch gradient descent versus stochastic gradient descent

Single Layer Neural Network - Adaptive Linear Neuron using linear (identity) activation function with batch gradient descent method

Single Layer Neural Network : Adaptive Linear Neuron using linear (identity) activation function with stochastic gradient descent (SGD)

Logistic Regression

VC (Vapnik-Chervonenkis) Dimension and Shatter

Bias-variance tradeoff

Maximum Likelihood Estimation (MLE)

Neural Networks with backpropagation for XOR using one hidden layer

minHash

tf-idf weight

Natural Language Processing (NLP): Sentiment Analysis I (IMDb & bag-of-words)

Natural Language Processing (NLP): Sentiment Analysis II (tokenization, stemming, and stop words)

Natural Language Processing (NLP): Sentiment Analysis III (training & cross validation)

Natural Language Processing (NLP): Sentiment Analysis IV (out-of-core)

Locality-Sensitive Hashing (LSH) using Cosine Distance (Cosine Similarity)




Artificial Neural Networks (ANN)

[Note] Sources are available at Github - Jupyter notebook files

1. Introduction

2. Forward Propagation

3. Gradient Descent

4. Backpropagation of Errors

5. Checking gradient

6. Training via BFGS

7. Overfitting & Regularization

8. Deep Learning I : Image Recognition (Image uploading)

9. Deep Learning II : Image Recognition (Image classification)

10 - Deep Learning III : Deep Learning III : Theano, TensorFlow, and Keras









Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master