Skip to content

Instantly share code, notes, and snippets.

@hospadar
Created February 25, 2015 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hospadar/46d493b243d7ca8a23e3 to your computer and use it in GitHub Desktop.
Save hospadar/46d493b243d7ca8a23e3 to your computer and use it in GitHub Desktop.
DFR Tokenizer example
from __future__ import print_function
import re, sys
from nltk import ngrams, tokenize, download
from argparse import ArgumentParser
"""
#USAGE:
#This python file illustrates the techniques that Data For Research (http://dfr.jstor.org/) uses to tokenize raw text and generate n-grams
#DFR uses the NLTK 'punkt' tokenizer which needs to be downloaded separately from the nltk package.
#To download and install NLTK and the training data:
pip install nltk
python -c "import nltk; nltk.download('punkt')"
#Once nltk is installed and set up, pipe some text into this script to get tokens in a tab-delimited format.
echo "an interesting sentence that you might want to tokenize. perhaps you want to tokenize two sentences" | python generate_ngrams.py 2
"""
"""
LICENSE:
The MIT License (MIT)
Copyright (c) <year> <copyright holders>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
#this is the pattern used to split tokens
tokenizer_pattern = '''(?x) ([A-Z]\.)+ | \w+(-\w+)* | \$?\d+(\.\d+)?%? | \.\.\. | [][.,;"'?():-_`]'''
#create an nltk tokenizer
tokenizer = tokenize.RegexpTokenizer(tokenizer_pattern)
#given a blob of text, get ngrams
def generate_ngrams(raw_text, n=1):
tokenized_sentences = get_tokenized_sentences(raw_text)
grams = {}
#nltk returns lists of tokenized sentences, turn those into ngrams (with the help of nltk)
for tokens in tokenized_sentences:
if n == 1:
for gram in tokens:
if gram.isalpha():
grams[(gram,)] = grams.get((gram,),0) + 1
else:
for gram in ngrams(tokens, n):
grams[gram] = grams.get(gram,0) + 1
sorted_grams = []
for gram, count in grams.items():
sorted_grams.append([' '.join(gram), count])
sorted_grams.sort(lambda y, x: cmp(x[1],y[1]))
return sorted_grams
def get_tokenized_sentences(raw_text):
tokenized_sentences = []
if raw_text:
#Normalize whitespace
raw_text = re.sub('\s+', ' ', raw_text)
#Attempt to re-connect word continuation hyphens
raw_text = re.sub('-\s+', '', raw_text)
for sentence in tokenize.sent_tokenize(raw_text):
#start with a token to signify sentence boundary
tokens = ['#']
for token in tokenizer.tokenize(sentence.lower()):
#Certain tokens (numbers and punctuation) are collapsed into common tokens
if token:
if (token.isalpha()):
tokens.append(token)
elif token.isdigit():
tokens.append('##')
else:
tokens.append('###')
#add a token to signify sentence boundary
tokens.append('#')
tokenized_sentences.append(tokens)
return tokenized_sentences
if __name__ == "__main__":
parser = ArgumentParser("Generate ngrams based on text fed into stdin")
parser.add_argument("n", nargs=1, help="How much n do you want your n-grams to have? 1 for wordcounts, 2 for bigrams, etc", type=int)
options = parser.parse_args()
for ngram in generate_ngrams(sys.stdin.read(), options.n[0]):
sys.stdout.write("{0}\t{1}\n".format(*ngram))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment