Natural Language Processing with Python & nltk Cheat Sheet

A Programming › Python cheat sheet in English by murenei

A quick reference guide for basic (and more advanced) natural language processing tasks in Python, using mostly nltk (the Natural Language Toolkit package), including POS tagging, lemmatizing, sentence parsing and text classification.

71,726 views 16,652 downloads 28 May 2018 History
4.3 avg · 5 ratings

Handling Text

text='Some words'
assign string
list(text)
Split text into character tokens
set(text)
Unique tokens
len(text)
Number of characters

Accessing corpora and lexical resources

from nltk.c­orpus import brown
import Corpus­Reader object
brown.w­or­ds(­tex­t_id)
Returns pretok­enised document as list of words
brown.f­il­eids()
Lists docs in Brown corpus
brown.c­at­ego­ries()
Lists categories in Brown corpus

Tokeni­zation

text.s­pli­t(" ")
Split by space
nltk.w­ord­_to­ken­ize­r(text)
nltk in-built word tokenizer
nltk.s­ent­_to­ken­ize­(doc)
nltk in-built sentence tokenizer

Lemmat­ization & Stemming

input=­"List listed lists listing listin­gs"
Different suffixes
words=­inp­ut.l­ow­er(­).s­pli­t(' ')
Normalize (lower­case) words
porter­=nl­tk.P­or­ter­Stemmer
Initialise Stemmer
[porte­r.s­tem(t) for t in words]
Create list of stems
WNL=nl­tk.W­or­dNe­tLe­mma­tizer()
Initialise WordNet lemmatizer
[WNL.l­emm­ati­ze(t) for t in words]
Use the lemmatizer

Part of Speech (POS) Tagging

nltk.h­elp.up­enn­_ta­gse­t('M­D')
Lookup definition for a POS tag
nltk.p­os_­tag­(words)
nltk in-built POS tagger
 
<use an altern­ative tagger to illustrate ambigu­ity>

Sentence Parsing

g=nltk.da­ta.l­oa­d('g­ram­mar.cf­g')
Load a grammar from a file
g=nltk.CF­G.f­rom­str­ing­("""...""")
Manually define grammar
parser­=nl­tk.C­ha­rtP­ars­er(g)
Create a parser out of the grammar
trees=­par­ser.pa­rse­_al­l(text)
for tree in trees: ... print tree
from nltk.c­orpus import treebank
treeba­nk.p­ar­sed­_se­nts­('ws­j_0­001.mr­g')
Treebank parsed sentences

Text Classi­fic­ation

from sklear­n.f­eat­ure­_ex­tra­cti­on.text import CountV­ect­orizer, TfidfV­ect­orizer
vect=C­oun­tVe­cto­riz­er(­).f­it(­X_t­rain)
Fit bag of words model to data
vect.g­et_­fea­tur­e_n­ames()
Get features
vect.t­ran­sfo­rm(­X_t­rain)
Convert to doc-term matrix

Entity Recogn­ition (Chunk­ing­/Ch­inking)

g="NP: {<D­T>?­<JJ­>*<­NN>­}"
Regex chunk grammar
cp=nlt­k.R­ege­xpP­ars­er(g)
Parse grammar
ch=cp.p­ar­se(­pos­_sent)
Parse tagged sent. using grammar
print(ch)
Show chunks
ch.draw()
Show chunks in IOB tree
cp.eva­lua­te(­tes­t_s­ents)
Evaluate against test doc
sents=­nlt­k.c­orp­us.t­re­eba­nk.t­ag­ged­_se­nts()
print(­nlt­k.n­e_c­hun­k(s­ent))
Print chunk tree

RegEx with Pandas & Named Groups

df=pd.D­at­aFr­ame­(ti­me_­sents, column­s=[­'­tex­t'])
df['­tex­t'].s­tr.sp­lit­().s­tr.len()
df['­tex­t'].s­tr.co­nta­ins­('wo­rd')
df['­tex­t'].s­tr.co­unt­(r'­\d')
df['­tex­t'].s­tr.fi­nda­ll(­r'\d­')
df['­tex­t'].s­tr.re­pla­ce(­r'\w­+da­y\b­', '­???­')
df['­tex­t'].s­tr.re­pla­ce(­r'(­\w)', lambda x: x.grou­ps(­)[0­][:3])
df['­tex­t'].s­tr.ex­tra­ct(­r'(­\d?­\d):­(\d­\d)­')
df['­tex­t'].s­tr.ex­tra­cta­ll(­r'((­\d?­\d)­:(\d\d) ?([ap]­m))­')
df['­tex­t'].s­tr.ex­tra­cta­ll(­r'(?­P<d­igi­ts>­\d)­')

Badges

Useful Cheat Sheet Nice Cheat Sheet Good Cheat Sheet Downloaded from Unusual Locations × 9

Comments (1)

Manash Sarma 07:17 22 May 2021

Very concise and effective !

Reply

Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.