Confrontare testo in Python con difflib
difflib è una funzione built-in di Python che ci consente di confrontare dei testi/sequenze di caratteri.
Non c'è da installare nulla, e contiene diverse funzioni interessanti.
In questo articolo vediamo qualche esempio.
Vi ho messo tutti il codice insieme con dei commenti:
from difflib import unified_diff, get_close_matches, HtmlDiff
testo_a = "Ciao come stai??"
testo_b = "Ciao come stai?"
# CONTROLLO I DUE TESTI E VERIFICO CHE SIANO UGUALI
diff = unified_diff(testo_a.splitlines(), testo_b.splitlines(), lineterm='')
print('n'.join(list(diff)))
# STESSO CONTROLLO DEL PRECEDENTE MA CON CREAZIONE REPORT IN HTML
html = HtmlDiff()
report = html.make_file(testo_a.splitlines(), testo_b.splitlines())
print(report)
with open("report.html", "w", encoding="utf-8") as f:
f.write(report)
# CONTROLLO DELLA SOMIGLIANZA TRA LA PAROLA INDICATA E QUELLE CONTENUTE NELLA LISTA
parole = ["calcio", "calciatore", "gioco", "calciato"]
close_match = get_close_matches('calc', parole)
print(close_match)
Enjoy!
python difflib
Commentami!