Skip to content

Instantly share code, notes, and snippets.

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 vi3k6i5/457f34f2e95b5d114a3bb538d33d30b3 to your computer and use it in GitHub Desktop.
Save vi3k6i5/457f34f2e95b5d114a3bb538d33d30b3 to your computer and use it in GitHub Desktop.
Benchmarking timing performance Keyword Extraction between regex (regex module) and flashtext
#!/bin/python
from flashtext.keyword import KeywordProcessor
import random
import string
import regex
import time
def get_word_of_length(str_length):
# generate a random word of given length
return ''.join(random.choice(string.ascii_lowercase) for _ in range(str_length))
# generate a list of 100K words of randomly chosen size
all_words = [get_word_of_length(random.choice([3, 4, 5, 6, 7, 8])) for i in range(100000)]
print('Count | FlashText | Regex ')
print('-------------------------------')
for keywords_length in range(0, 20001, 1000):
# chose 5000 terms and create a string to search in.
all_words_chosen = random.sample(all_words, 5000)
story = ' '.join(all_words_chosen)
# get unique keywords from the list of words generated.
unique_keywords_sublist = list(set(random.sample(all_words, keywords_length)))
# compile regex
compiled_re = regex.compile('|'.join([r'\b' + keyword + r'\b' for keyword in unique_keywords_sublist]))
# add keywords to flashtext
keyword_processor = KeywordProcessor()
keyword_processor.add_keywords_from_list(unique_keywords_sublist)
# time the modules
start = time.time()
_ = keyword_processor.extract_keywords(story)
mid = time.time()
_ = compiled_re.findall(story)
end = time.time()
# print output
print(str(keywords_length).ljust(6), '|',
"{0:.5f}".format(mid - start).ljust(9), '|',
"{0:.5f}".format(end - mid).ljust(9), '|',)
# Count | FlashText | Regex
# -------------------------------
# 0 | 0.01503 | 0.00451 |
# 1000 | 0.01770 | 0.11515 |
# 2000 | 0.02162 | 0.28438 |
# 3000 | 0.02005 | 0.40018 |
# 4000 | 0.01825 | 0.40201 |
# 5000 | 0.02166 | 0.47453 |
# 6000 | 0.02271 | 0.61018 |
# 7000 | 0.01948 | 0.63136 |
# 8000 | 0.01917 | 0.71915 |
# 9000 | 0.01952 | 1.05328 |
# 10000 | 0.01971 | 1.34943 |
# 11000 | 0.01991 | 1.17387 |
# 12000 | 0.02020 | 1.63653 |
# 13000 | 0.02274 | 2.18791 |
# 14000 | 0.02174 | 2.82363 |
# 15000 | 0.02084 | 1.87638 |
# 16000 | 0.02172 | 2.01723 |
# 17000 | 0.02102 | 2.04743 |
# 18000 | 0.02119 | 2.99934 |
# 19000 | 0.02240 | 3.16921 |
# 20000 | 0.02227 | 3.75960 |
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment