Cercare o estrarre testo in Python con FlashText
In Python abbiamo diversi modi/librerie per cercare delle parole all'interno di un testo.
Una delle possibilità è usare FlashText.
Per l'installazione possiamo usare pip:
pip install flashtext
Qui sotto un pò di esempi:
from flashtext import KeywordProcessor
string_search = ['testo', 'una fase', 'ciao']
text = 'Ciao! Questo è un testo con molte frasi'
kp = KeywordProcessor()
for ss in string_search:
kp.add_keyword(ss)
found = kp.extract_keywords(text)
print(found)
kp.add_keyword('frasi', 'parole')
substitute = kp.replace_keywords(text)
print(substitute)
In questo codice ciao e Ciao vengono trattati alla stessa maniera.
Se volessimo fare ricerce case sensitive:
from flashtext import KeywordProcessor
string_search = ['testo', 'una fase', 'ciao']
text = 'Ciao! Questo è un testo con molte frasi'
kp = KeywordProcessor(case_sensitive=True)
for ss in string_search:
kp.add_keyword(ss)
found = kp.extract_keywords(text)
print(found)
kp.add_keyword('frasi', 'parole')
substitute = kp.replace_keywords(text)
print(substitute)
Enjoy!
python pip flashtext
Commentami!