Skip to content

Instantly share code, notes, and snippets.

@dlamblin
Last active May 14, 2024 15:12
Show Gist options
  • Save dlamblin/926f900ea6ebdaaba2805a4e793cf0f5 to your computer and use it in GitHub Desktop.
Save dlamblin/926f900ea6ebdaaba2805a4e793cf0f5 to your computer and use it in GitHub Desktop.
Python N-Gram for characters in string
"""
n-gram of a string by characters (not by words)
takes all args as input unless the first two args are numbers which are in
order, then it assume these are min and max length. Default min max is 2 - 60
"""
def ngram(inp='', mn=2, mx=60):
"""
Returns a list of all segments of input inp that range
in length from mn to mx characters.
List comprehension version of the below code runs faster than it:
def ngram(inp='', mn=2, mx=60):
out = []
for i in range(0, len(inp) + 1 - mn):
for j in range(i + mn, min(i + mx + 1, len(inp) + 1)):
out.append(inp[i:j])
return out
"""
return [
inp[i:j]
for i in range(0, len(inp) + 1 - mn)
for j in range(i + mn, min(i + mx + 1, len(inp) + 1))
]
def main():
from sys import argv
mn = 2
mx = 60
if len(argv) < 2:
return
if len(argv) > 3:
try:
pmn = int(argv[1])
pmx = int(argv[2])
if pmn < pmx:
mn = pmn
mx = pmx
argv.pop(0)
argv.pop(0)
except ValueError:
pass
res = ngram(inp=" ".join(argv[1:]), mn=mn, mx=mx)
print(res)
print('{} values.'.format(len(res)))
print('{} unique values.'.format(len({k: 1 for k in res}.keys())))
if __name__ == '__main__':
main()
$ python2 ~/ngram.py cs_sales
['cs', 'cs_', 'cs_s', 'cs_sa', 'cs_sal', 'cs_sale', 'cs_sales', 's_', 's_s', 's_sa', 's_sal', 's_sale', 's_sales', '_s', '_sa', '_sal', '_sale', '_sales', 'sa', 'sal', 'sale', 'sales', 'al', 'ale', 'ales', 'le', 'les', 'es']
28 values.
28 unique values.
$ python3 ~/ngram.py 1 5 This is just a sentence.
['T', 'Th', 'Thi', 'This', 'This ', 'h', 'hi', 'his', 'his ', 'his i', 'i', 'is', 'is ', 'is i', 'is is', 's', 's ', 's i', 's is', 's is ', ' ', ' i', ' is', ' is ', ' is j', 'i', 'is', 'is ', 'is j', 'is ju', 's', 's ', 's j', 's ju', 's jus', ' ', ' j', ' ju', ' jus', ' just', 'j', 'ju', 'jus', 'just', 'just ', 'u', 'us', 'ust', 'ust ', 'ust a', 's', 'st', 'st ', 'st a', 'st a ', 't', 't ', 't a', 't a ', 't a s', ' ', ' a', ' a ', ' a s', ' a se', 'a', 'a ', 'a s', 'a se', 'a sen', ' ', ' s', ' se', ' sen', ' sent', 's', 'se', 'sen', 'sent', 'sente', 'e', 'en', 'ent', 'ente', 'enten', 'n', 'nt', 'nte', 'nten', 'ntenc', 't', 'te', 'ten', 'tenc', 'tence', 'e', 'en', 'enc', 'ence', 'ence.', 'n', 'nc', 'nce', 'nce.', 'c', 'ce', 'ce.', 'e', 'e.', '.']
110 values.
95 unique values.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment