concept NLTK in category dask

appears as: NLTK
Data Science with Python and Dask

This is an excerpt from Manning's book Data Science with Python and Dask.

Configuring NLTK

For the examples in chapters 9 and 10, you will need to download some additional data for NLTK. To do this, run the following command in your terminal window.

Listing A.3 Downloading NLTK data
python -m nltk.downloader all

If you run into issues, try running the command with elevated privileges (either using sudo on a Unix/Linux/MacOS system or running Command Prompt as Administrator in Windows). After running this command, you are ready to use NLTK.

Using NLTK and Dask Bags, find the most commonly mentioned phrases in the text of both positive and negative reviews for Amazon products to see what reviewers frequently discuss in their reviews.

Before we jump in, make sure you have NLTK set up properly in your Python environment. See the appendix for instructions on installing and configuring NLTK. With NLTK installed, we need to import the relevant modules into our current workspace; then we’ll create a few functions to help us along with the data prep.

Listing 9.26 Extract and filter functions
from nltk.corpus import stopwords 
from nltk.tokenize import RegexpTokenizer
from functools import partial

tokenizer = RegexpTokenizer(r'\w+')    #1  

def extract_reviews(element):    #2  
    return element['review/text'].lower()

def filter_stopword(word, stopwords):    #3  
    return word not in stopwords

def filter_stopwords(tokens, stopwords):    #4  
    return list(filter(partial(filter_stopword, stopwords=stopwords), tokens))

stopword_set = set(stopwords.words('english'))    #5  

#1   Create a tokenizer using a regex expression that will extract only words; this means punctuation, numbers, and so forth will be discarded.
#2   This function takes an element from the Bag, gets the review text, and changes all letters to lowercase; this is important because Python is case-sensitive.
#3   This function returns True if the word is not in the list of stopwords.
#4   This function uses the filter function above it to check every word in a list of words (tokens) and discard the word if it is a stopword.
#5   Get the list of English stopwords from NLTK and cast it from a list to a set; using a set is faster than a list in this comparison.