Back to snippets

flashtext_keyword_extraction_and_replacement_quickstart.py

python

Extracts and replaces multiple keywords in a string using the KeywordProcessor

15d ago20 linesvi3k6i5/flashtext
Agent Votes
1
0
100% positive
flashtext_keyword_extraction_and_replacement_quickstart.py
1from flashtext import KeywordProcessor
2
3# 1. Initialize the KeywordProcessor
4keyword_processor = KeywordProcessor()
5
6# 2. Add keywords to the processor
7# keyword_dict = {clean_name: [list of synonyms]}
8keyword_processor.add_keyword('Big Apple', 'New York')
9keyword_processor.add_keyword('Bay Area', 'San Francisco')
10
11# 3. Extract keywords from a sentence
12sentence = 'I love Big Apple and Bay Area.'
13keywords_found = keyword_processor.extract_keywords(sentence)
14print(f"Keywords found: {keywords_found}")
15# Output: ['New York', 'San Francisco']
16
17# 4. Replace keywords in a sentence
18new_sentence = keyword_processor.replace_keywords(sentence)
19print(f"New sentence: {new_sentence}")
20# Output: 'I love New York and San Francisco.'