Skip to content

Instantly share code, notes, and snippets.

@lisanka93
Created July 13, 2020 15:53
Show Gist options
  • Save lisanka93/7b963f2ed1f3da76cfb44a97a52a82a1 to your computer and use it in GitHub Desktop.
Save lisanka93/7b963f2ed1f3da76cfb44a97a52a82a1 to your computer and use it in GitHub Desktop.
NLTK ngrams, bigrams and trigrams
from nltk.util import ngrams, word_tokenize, bigrams, trigrams
sen = "Dummy sentence to demonstrate bigrams"
nltk_tokens = word_tokenize(sen) #using tokenize from NLKT and not split() because split() does not take into account punctuation
#splitting sentence into bigrams and trigrams
print(list(bigrams(nltk_tokens)))
print(list(trigrams(nltk_tokens)))
#creating a dictionary that shows occurances of n-grams in text
n_gram = 5
n_gram_dic = dict(Counter(ngrams(all_words.split(), n_gram)))
print(n_gram_dic)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment