Quick implementation of character n-grams for word
Asked Answered
B

4

23

I wrote the following code for computing character bigrams and the output is right below. My question is, how do I get an output that excludes the last character (ie t)? and is there a quicker and more efficient method for computing character n-grams?

b='student'
>>> y=[]
>>> for x in range(len(b)):
    n=b[x:x+2]
    y.append(n)
>>> y
['st', 'tu', 'ud', 'de', 'en', 'nt', 't']

Here is the result I would like to get:['st','tu','ud','de','nt]

Thanks in advance for your suggestions.

Broadbent answered 6/9, 2013 at 12:39 Comment(1)
Possible duplicate of Fast/Optimize N-gram implementations in pythonTitanism
M
47

To generate bigrams:

In [8]: b='student'

In [9]: [b[i:i+2] for i in range(len(b)-1)]
Out[9]: ['st', 'tu', 'ud', 'de', 'en', 'nt']

To generalize to a different n:

In [10]: n=4

In [11]: [b[i:i+n] for i in range(len(b)-n+1)]
Out[11]: ['stud', 'tude', 'uden', 'dent']
Marriage answered 6/9, 2013 at 12:47 Comment(0)
T
13

Try zip:

>>> def word2ngrams(text, n=3, exact=True):
...   """ Convert text into character ngrams. """
...   return ["".join(j) for j in zip(*[text[i:] for i in range(n)])]
... 
>>> word2ngrams('foobarbarblacksheep')
['foo', 'oob', 'oba', 'bar', 'arb', 'rba', 'bar', 'arb', 'rbl', 'bla', 'lac', 'ack', 'cks', 'ksh', 'she', 'hee', 'eep']

but do note that it's slower:

import string, random, time

def zip_ngrams(text, n=3, exact=True):
  return ["".join(j) for j in zip(*[text[i:] for i in range(n)])]

def nozip_ngrams(text, n=3):
    return [text[i:i+n] for i in range(len(text)-n+1)]

# Generate 10000 random strings of length 100.
words = [''.join(random.choice(string.ascii_uppercase) for j in range(100)) for i in range(10000)]

start = time.time()
x = [zip_ngrams(w) for w in words]
print time.time() - start

start = time.time()
y = [nozip_ngrams(w) for w in words]
print time.time() - start        

print x==y

[out]:

0.314492940903
0.197558879852
True
Titanism answered 15/3, 2014 at 17:15 Comment(0)
U
2

Although late, NLTK has an inbuilt function that implements ngrams

# python 3
from nltk import ngrams
["".join(k1) for k1 in list(ngrams("hello world",n=3))]

['hel', 'ell', 'llo', 'lo ', 'o w', ' wo', 'wor', 'orl', 'rld']
Usurer answered 13/7, 2021 at 5:20 Comment(0)
O
0

Ths fucntion gives you ngrams for n = 1 to n:

def getNgrams(sentences, n):
    ngrams = []
    for sentence in sentences:
        _ngrams = []
        for _n in range(1,n+1):
            for pos in range(1,len(sentence)-_n):
                _ngrams.append([sentence[pos:pos+_n]])
        ngrams.append(_ngrams)
    return ngrams
Overgrowth answered 1/4, 2018 at 6:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.