diff --git a/Ela_Spacy.py b/Ela_Spacy.py index 375f779..4bcaa21 100644 --- a/Ela_Spacy.py +++ b/Ela_Spacy.py @@ -385,7 +385,25 @@ def Ela_stemmize_search(tab_tokens): ''' print("AVANT COORECTION ORH ="+str(mot)+" ==> APRES = "+unidecode(str(MYSY_GV.spell.correction(mot)))) corrected_str = str(MYSY_GV.spell.correction(mot)) + + + ''' + Evolution du 02/05/22 : + On supprime la stemisation, mais on va chercher le masculin singulier du mot + Puis on regarde si masculin singulier existe dans la la collecion "elaindex" + + + ''' + corrected_str_unicode = unidecode(corrected_str) + status, corrected_str_masc_sing = mycommon.GetMasculinSingulier(corrected_str_unicode) + if( status is True ): + tab_ret_val.append(corrected_str_masc_sing) + + ''' + cette ligne est commentées pour eviter la stemisation. + evolution du 02/05/22 tab_ret_val.append( unidecode (str(MYSY_GV.stemmer.stem(corrected_str)))) + ''' print(" STMISATION TAB = "+str(tab_ret_val)) @@ -417,6 +435,7 @@ def ela_index_record_field(lines, class_id, source_field = ""): ''' coll_name = MYSY_GV.dbname['elaindex'] + coll_name_StopWord = MYSY_GV.dbname['mysystopwords'] # check default value of parameter : source_field if len(str(source_field)) == 0 : @@ -428,14 +447,22 @@ def ela_index_record_field(lines, class_id, source_field = ""): ''' Ajout des indexe + La fontion Tokenize fait les fonctions suivantes : + - Ela_Remove_Bad_Pattern + - Ela_Remove_Ponct_Special_Caractere + - Unidecode ''' status, tab_tokens = Ela_Tokenize(lines) if( status is False): return False - #print(" AFFICHAGE TAB TOKEN") - #print(tab_tokens) - #print(" FINNN TAB TOKEN") + ''' + Ajout des indexe + La fontion Tokenize fait les fonctions suivantes : + - Ela_Remove_Bad_Pattern + - Ela_Remove_Ponct_Special_Caractere + - Unidecode + ''' status, tab_tokens2 = Ela_remove_stop_words(tab_tokens) if (status is False): return False @@ -444,6 +471,26 @@ def ela_index_record_field(lines, class_id, source_field = ""): if (status is False): return False + print(" AVANT STEM " + str(tab_tokens3)) + # Mettre en unicode et virer d'autre stop word + tab_tokens3_unicode = [] + for val in tab_tokens3: + val_unicode = unidecode(val) + # print(' val_unicode = '+str(val_unicode)) + + ''' + Verification que le mot n'est pas dans les nouveau stopwords''' + val_tmp = coll_name_StopWord.count_documents({'stop_word': str(val_unicode)}) + if (val_tmp <= 0): + ''' + Recuperation du masculin singulier du mot''' + status, newword = mycommon.GetMasculinSingulier(str(val_unicode)) + if (status is True): + tab_tokens3_unicode.append(newword) + + print("TTTTT " + str(tab_tokens3_unicode)) + + status, tab_tokens4 = Ela_stemmize_Class(tab_tokens3) if (status is False): return False @@ -452,7 +499,7 @@ def ela_index_record_field(lines, class_id, source_field = ""): #tab_tokens4 = Ela_remove_ponct(tab_tokens4) # Enregistrement dans la base mongodb - Ela_list_to_mongo(tab_tokens4,class_id, source_field) + Ela_list_to_mongo(tab_tokens3_unicode,class_id, source_field) size_tab = len(tab_tokens4) #print("size_tab = " + str(size_tab)) @@ -487,16 +534,28 @@ def YTUBES_ela_index_record_field(lines, class_id, source_field = ""): source_field = 'default' myquery = {"id_formation": class_id, "source_field":source_field} + + #print(" Mydelete Query = "+str(myquery)) delete_row = coll_name.delete_many(myquery) #mycommon.myprint(" elaindex - "+str(delete_row.deleted_count)+" documents deleted. Training ==> "+str(class_id)+" ") ''' Ajout des indexe + La fontion Tokenize fait les fonctions suivantes : + - Ela_Remove_Bad_Pattern + - Ela_Remove_Ponct_Special_Caractere + - Unidecode ''' status, tab_tokens = Ela_Tokenize(lines) if( status is False): return False + ''' + la fonction Ela_remove_stop_words supprimer les stops + cette ligne et deprecié remplacé par une ligne plus loin + qui lit dans la collection "mysystopwords" + + ''' status, tab_tokens2 = Ela_remove_stop_words(tab_tokens) if (status is False): return False @@ -505,18 +564,27 @@ def YTUBES_ela_index_record_field(lines, class_id, source_field = ""): if (status is False): return False - print(" AVANT STEM ") + print(" AVANT STEM "+str(tab_tokens3)) + # Mettre en unicode et virer d'autre stop word tab_tokens3_unicode = [] for val in tab_tokens3: val_unicode = unidecode(val) + #print(' val_unicode = '+str(val_unicode)) + + ''' + Verification que le mot n'est pas dans les nouveau stopwords''' val_tmp = coll_name_StopWord.count_documents({'stop_word': str(val_unicode)}) if( val_tmp <= 0 ): - tab_tokens3_unicode.append(val_unicode) + ''' + Recuperation du masculin singulier du mot''' + status, newword = mycommon.GetMasculinSingulier(str(val_unicode)) + if( status is True): + tab_tokens3_unicode.append(newword) - #print(str(tab_tokens3_unicode)) + print("TTTTT "+str(tab_tokens3_unicode)) status, tab_tokens4 = Ela_stemmize_Class(tab_tokens3_unicode) if (status is False): return False @@ -525,7 +593,7 @@ def YTUBES_ela_index_record_field(lines, class_id, source_field = ""): #tab_tokens4 = Ela_remove_ponct(tab_tokens4) # Enregistrement dans la base mongodb - YTUBES_Ela_list_to_mongo(tab_tokens4,class_id, source_field) + YTUBES_Ela_list_to_mongo(tab_tokens3_unicode,class_id, source_field) size_tab = len(tab_tokens4) #print("size_tab = " + str(size_tab)) diff --git a/GlobalVariable.py b/GlobalVariable.py index 9e72e00..3f020cb 100644 --- a/GlobalVariable.py +++ b/GlobalVariable.py @@ -76,3 +76,5 @@ spell_fr = Speller(lang='fr') Repertoire de stockage de video YouTubes ''' YTUBES_ENSCRIPT_LOCATION = "" + + diff --git a/data_indexees.csv b/data_indexees.csv index 924571b..c5972e9 100644 --- a/data_indexees.csv +++ b/data_indexees.csv @@ -1,29 +1,4 @@ ,index,mots,occurence,moyenne,id_formation,source_field -0,0,driv,1,0.03,PUjv9Ua5db4,description -1,1,cump,1,0.03,PUjv9Ua5db4,description -2,2,resultat,1,0.03,PUjv9Ua5db4,description -3,3,cout,4,0.12,PUjv9Ua5db4,description -4,4,inventair,1,0.03,PUjv9Ua5db4,description -5,5,fil,1,0.03,PUjv9Ua5db4,description -6,6,repartit,1,0.03,PUjv9Ua5db4,description -7,7,revient,1,0.03,PUjv9Ua5db4,description -8,8,stock,1,0.03,PUjv9Ua5db4,description -9,9,distribu,1,0.03,PUjv9Ua5db4,description -10,10,googl,1,0.03,PUjv9Ua5db4,description -11,11,revis,1,0.03,PUjv9Ua5db4,description -12,12,http,1,0.03,PUjv9Ua5db4,description -13,13,approvision,1,0.03,PUjv9Ua5db4,description -14,14,comptabl,1,0.03,PUjv9Ua5db4,description -15,15,indirect,1,0.03,PUjv9Ua5db4,description -16,16,analyt,2,0.06,PUjv9Ua5db4,description -17,17,tableau,1,0.03,PUjv9Ua5db4,description -18,18,method,1,0.03,PUjv9Ua5db4,description -19,19,charg,1,0.03,PUjv9Ua5db4,description -20,20,product,1,0.03,PUjv9Ua5db4,description -21,21,usp,1,0.03,PUjv9Ua5db4,description -22,22,support,1,0.03,PUjv9Ua5db4,description -23,23,sujet,1,0.03,PUjv9Ua5db4,description -24,24,etap,1,0.03,PUjv9Ua5db4,description -25,25,view,1,0.03,PUjv9Ua5db4,description -26,26,sharing,1,0.03,PUjv9Ua5db4,description -27,27,com,1,0.03,PUjv9Ua5db4,description +0,0,fondamentau,1,0.33,8866,title +1,1,publique,1,0.33,8866,title +2,2,comptabilite,1,0.33,8866,title diff --git a/ela_index_bdd_classes.py b/ela_index_bdd_classes.py index 758deb7..e1436b3 100644 --- a/ela_index_bdd_classes.py +++ b/ela_index_bdd_classes.py @@ -532,9 +532,16 @@ def ela_recherche_tokens(sentence): # collection collection = MYSY_GV.dbname["elaindex"] - print(" mot recherché tab_tokens4 = "+str(tab_tokens4)) + print(" mot recherché tab_tokens4 (initialement) = "+str(tab_tokens4)) - pipe2 = [{ '$match': { 'mots': { '$in': tab_tokens4 } } }, + status, new_tab_tokens4 = mysy_recherche_levenshtein(tab_tokens4) + if( status is False): + mycommon.myprint(str(inspect.stack()[0][3]) + " Recherche : mysy_recherche_levenshtein return FALSE ") + return [] + + print(" ### les nouveaux mots recherchés new_tab_tokens4 = " + str(new_tab_tokens4)) + + pipe2 = [{ '$match': { 'mots': { '$in': new_tab_tokens4 } } }, { '$group': { '_id': "$id_formation", 'count_class': {'$sum': 1}, @@ -555,6 +562,63 @@ def ela_recherche_tokens(sentence): return tab_training_id +''' +Cette fonction essayer de faire une recherche de leveinstein +elle prend une liste mot : +pr chaque mot, +1 - elle prends les 3 premier caractère +2 - recherche ceux qui correspondent +3 - pour chaque mot trouvé, faire un distance de levein et voir + +puis elle retourne la liste des mots trouvé dans la table elaindex + +Regles fonctionnelles : +Si 0 < len(mot) <= 3 ==> Recherche strict à faire +Si 3 < len(mot) <= 5 ==> Recherche avec une distance de 1 +Si 5 < len(mot) <= 10 ==> Recherche avec une distance de 2 +Si 10 < len(mot) ==> Recherche avec une distance de 3 +''' +def mysy_recherche_levenshtein(tab_mot): + try: + + coll_name = MYSY_GV.dbname['elaindex'] + training_mots = [] + + for mot in tab_mot: + if( len( mot ) > 2): + mot_first_caract = mot[0:3] + print(" Traitement de " + str(mot) + " = 3 first => " + str(mot_first_caract)) + + v = {'$regex': "^" + mot_first_caract} + print("v = " + str(v)) + + for x in coll_name.find({'mots': v}): + cmp_levenshtein = int(mycommon.levenshtein(mot, str(x['mots']))) + + + if( len(mot) <= 5 and cmp_levenshtein <= 1): + if( str(x['mots']) not in training_mots): + training_mots.append( str(x['mots']) ) + + elif( len(mot) <= 10 and cmp_levenshtein <= 2): + if( str(x['mots']) not in training_mots): + training_mots.append( str(x['mots']) ) + + elif ( cmp_levenshtein <= 3): + if (str(x['mots']) not in training_mots): + training_mots.append(str(x['mots'])) + + elif (cmp_levenshtein > 3): + print(" KOO cmp_levenshtein : " + mot + " CMP " + str(x['mots']) + " = " + str(cmp_levenshtein) + + " ==> id_formation" + str(x['id_formation']) + " ==> occurrence = " + str(x['occurence'])) + + + return True, training_mots + + except Exception as e: + exc_type, exc_obj, exc_tb = sys.exc_info() + mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno)) + return False, None ''' @@ -593,11 +657,20 @@ def ela_recherche_tokens_source_field(sentence, source_fied=""): if (status is False): return False + ''' + note : 26/03 : Faire evolution la fonction ici pour + gerer les mots qui ne doivent pas etre racinisé comme le cas du mot "Responsive" + + De manière plus globale, il faudrait exclure certains mot de la racinisation. + + ''' + print(" VERIF : " + str(tab_tokens3)) + status, tab_tokens4 = ls.Ela_stemmize_search(tab_tokens3) if (status is False): return False - + print(" VERIF APRES STEMISATION : " + str(tab_tokens4)) tab_tokens4.sort() @@ -608,8 +681,15 @@ def ela_recherche_tokens_source_field(sentence, source_fied=""): ''' collection = MYSY_GV.dbname["elaindex"] + print(" mot recherché tab_tokens4 (initialement) = " + str(tab_tokens4)) + status, new_tab_tokens4 = mysy_recherche_levenshtein(tab_tokens4) + if (status is False): + mycommon.myprint(str(inspect.stack()[0][3]) + " Recherche : mysy_recherche_levenshtein return FALSE ") + return [] - for token in tab_tokens4: + print(" ### les nouveaux mots recherchés new_tab_tokens4 = " + str(new_tab_tokens4)) + + for token in new_tab_tokens4: print(" #### Token rechercher dans l'index est : '"+str(token)+"' et le source_field = '"+str(source_fied)+"' ") for doc in collection.find({"mots":token, "source_field":source_fied}): #print(" Trouvé dans le cours N° "+str(doc["id_formation"])) diff --git a/ela_output_test_file_pandas_2.txt b/ela_output_test_file_pandas_2.txt index 66de7c5..518052a 100644 --- a/ela_output_test_file_pandas_2.txt +++ b/ela_output_test_file_pandas_2.txt @@ -1,29 +1,4 @@ mots occurence moyenne id_formation source_field -0 driv 1 0.03 PUjv9Ua5db4 description -1 cump 1 0.03 PUjv9Ua5db4 description -2 resultat 1 0.03 PUjv9Ua5db4 description -3 cout 4 0.12 PUjv9Ua5db4 description -4 inventair 1 0.03 PUjv9Ua5db4 description -5 fil 1 0.03 PUjv9Ua5db4 description -6 repartit 1 0.03 PUjv9Ua5db4 description -7 revient 1 0.03 PUjv9Ua5db4 description -8 stock 1 0.03 PUjv9Ua5db4 description -9 distribu 1 0.03 PUjv9Ua5db4 description -10 googl 1 0.03 PUjv9Ua5db4 description -11 revis 1 0.03 PUjv9Ua5db4 description -12 http 1 0.03 PUjv9Ua5db4 description -13 approvision 1 0.03 PUjv9Ua5db4 description -14 comptabl 1 0.03 PUjv9Ua5db4 description -15 indirect 1 0.03 PUjv9Ua5db4 description -16 analyt 2 0.06 PUjv9Ua5db4 description -17 tableau 1 0.03 PUjv9Ua5db4 description -18 method 1 0.03 PUjv9Ua5db4 description -19 charg 1 0.03 PUjv9Ua5db4 description -20 product 1 0.03 PUjv9Ua5db4 description -21 usp 1 0.03 PUjv9Ua5db4 description -22 support 1 0.03 PUjv9Ua5db4 description -23 sujet 1 0.03 PUjv9Ua5db4 description -24 etap 1 0.03 PUjv9Ua5db4 description -25 view 1 0.03 PUjv9Ua5db4 description -26 sharing 1 0.03 PUjv9Ua5db4 description -27 com 1 0.03 PUjv9Ua5db4 description \ No newline at end of file +0 fondamentau 1 0.33 8866 title +1 publique 1 0.33 8866 title +2 comptabilite 1 0.33 8866 title \ No newline at end of file diff --git a/main.py b/main.py index e6731fc..9878899 100644 --- a/main.py +++ b/main.py @@ -23,13 +23,14 @@ from flask import Flask, render_template, request, redirect, url_for import articles_avis as aa import GlobalVariable as MYSY_GV import youtubes_analyse as YTA - +import test_perso as TP app = Flask(__name__) cors = CORS(app, resources={r"/foo": {"origins": "*"}}) app.config['CORS_HEADERS'] = 'Content-Type' app.config['UPLOAD_FOLDER'] = MYSY_GV.upload_folder +app.env = "Production" @app.before_request def before_request(): @@ -996,15 +997,23 @@ def send_mail_delete_user(): status, result = eua.send_mail_delete_user(payload) return jsonify(status=status, message=result) + +''' +Cette API pour des tests perso +''' +@app.route('/myclass/api/mysy_recherche_levenshtein_orig/', methods=['GET','POST']) +@crossdomain(origin='*') +def mysy_recherche_levenshtein_orig(): + # On recupere le corps (payload) de la requete + payload = request.form.to_dict() + print(" ### payload = ", payload) + status, result = TP.mysy_recherche_levenshtein_orig() + return jsonify(status=status, message=result) + if __name__ == '__main__': print(" debut api") context = SSL.Context(SSL.SSLv23_METHOD) - - app.run(host='localhost', port=5000, debug=True, threaded=True) - #app.run(host='192.168.1.21', port=5000, debug=True) - #app.run(host='localhost', port=5000, debug=True) - # app.run(host='::', port=5000, debug=True) diff --git a/prj_common.py b/prj_common.py index 0152574..bc16f75 100644 --- a/prj_common.py +++ b/prj_common.py @@ -18,6 +18,7 @@ from unidecode import unidecode import GlobalVariable as MYSY_GV from serpapi import GoogleSearch import prj_common as mycommon +import re def myprint(message = ""): @@ -270,33 +271,39 @@ def similaire(): def levenshtein(mot1,mot2): - # ligne_i est un tableau tel que tout au long de l'algorithme, - # ligne_i[k] contienne la distance de levenshtein entre les k premières lettres de mot1 - # et les i premières lettres de mot2 - # Au début, i=0, et la distance entre les k premières lettres de mot1 et la chaîne vide - # vaut bien sûr k. (il faut faire k suppressions pour passer des k premières lettres de mot1 - # à la chaîne vide) - ligne_i = [ k for k in range(len(mot1)+1) ] - # i va ensuite varier de 1 à len(mot2) - for i in range(1, len(mot2) + 1): - # i vient d'être incrémenté. On stocke dans ligne_prec la valeur de la ligne numéro i-1 - ligne_prec = ligne_i - # On crée la nouvelle ligne, dont le premier élément (l'élement numéro 0) doit être - # la distance de levenshtein entre la chaîne vide ("") et les i premières lettres de mot2, soit i - # (il faut faire i additions pour passer de la chaîne vide aux i premières lettres de mot2) - ligne_i = [i]*(len(mot1)+1) - # On va ensuite remplir le reste de la ligne i, c'est-à-dire calculer ligne_i[k] pour k allant de 1 à len(mot1) - for k in range(1,len(ligne_i)): - # La variable cout vaut 0 si la kième lettre de mot1 est la même que la ième lettre de mot2, et 1 sinon - #La kième lettre de mot1 s'obtient avec mot1[k-1], les indices commencent à 0 - cout = int(mot1[k-1] != mot2[i-1]) - #Voilà enfin le sel de l'algorithme, le calcul de ligne_i[k] pour i et k quelconques, - # connaissant ligne_prec[k-1], ligne_prec[k] et ligne_i[k-1] - ligne_i[k] = min(ligne_i[k-1] + 1, ligne_prec[k] + 1, ligne_prec[k-1] + cout) - # Lorsque l'on sort de la boucle, i vaut len(mot2) - #Ce que l'on cherche est la distance de levenshtein entre les len(mot1) premières lettres de mot1 - # et les len(mot2) premières lettres de mot2, qui est stockée dans ligne_i[len(mot1)] - return ligne_i[len(mot1)] + try: + # ligne_i est un tableau tel que tout au long de l'algorithme, + # ligne_i[k] contienne la distance de levenshtein entre les k premières lettres de mot1 + # et les i premières lettres de mot2 + # Au début, i=0, et la distance entre les k premières lettres de mot1 et la chaîne vide + # vaut bien sûr k. (il faut faire k suppressions pour passer des k premières lettres de mot1 + # à la chaîne vide) + ligne_i = [ k for k in range(len(mot1)+1) ] + # i va ensuite varier de 1 à len(mot2) + for i in range(1, len(mot2) + 1): + # i vient d'être incrémenté. On stocke dans ligne_prec la valeur de la ligne numéro i-1 + ligne_prec = ligne_i + # On crée la nouvelle ligne, dont le premier élément (l'élement numéro 0) doit être + # la distance de levenshtein entre la chaîne vide ("") et les i premières lettres de mot2, soit i + # (il faut faire i additions pour passer de la chaîne vide aux i premières lettres de mot2) + ligne_i = [i]*(len(mot1)+1) + # On va ensuite remplir le reste de la ligne i, c'est-à-dire calculer ligne_i[k] pour k allant de 1 à len(mot1) + for k in range(1,len(ligne_i)): + # La variable cout vaut 0 si la kième lettre de mot1 est la même que la ième lettre de mot2, et 1 sinon + #La kième lettre de mot1 s'obtient avec mot1[k-1], les indices commencent à 0 + cout = int(mot1[k-1] != mot2[i-1]) + #Voilà enfin le sel de l'algorithme, le calcul de ligne_i[k] pour i et k quelconques, + # connaissant ligne_prec[k-1], ligne_prec[k] et ligne_i[k-1] + ligne_i[k] = min(ligne_i[k-1] + 1, ligne_prec[k] + 1, ligne_prec[k-1] + cout) + # Lorsque l'on sort de la boucle, i vaut len(mot2) + #Ce que l'on cherche est la distance de levenshtein entre les len(mot1) premières lettres de mot1 + # et les len(mot2) premières lettres de mot2, qui est stockée dans ligne_i[len(mot1)] + return ligne_i[len(mot1)] + + except Exception as e: + exc_type, exc_obj, exc_tb = sys.exc_info() + mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno)) + return False, None ''' @@ -475,7 +482,7 @@ def Get_Extended_Result(sentence=None): status = RunSearchAPI(sentence, external_code_prefixe) if( status is False): - return True, list_extended + return False, list_extended return True, external_code_prefixe except Exception as e: @@ -503,6 +510,13 @@ def RunSearchAPI(search_text=None, external_code_prefixe=None): } mycommon.myprint("######## PARAM RunSearchAPI = "+str(params)) + + ''' + return false prematuré pour eviter de consommer les credits de l'API + ''' + return False + + search = GoogleSearch(params) results = search.get_dict() organic_results = results['organic_results'] @@ -514,6 +528,7 @@ def RunSearchAPI(search_text=None, external_code_prefixe=None): for val in organic_results: cmpt = cmpt +1 mydata = {} + ''' print("External_code = " + str(val['title'])) print("Title = "+str(val['title'])) print("url = " + str(val['link'])) @@ -522,18 +537,26 @@ def RunSearchAPI(search_text=None, external_code_prefixe=None): if ("snippet_highlighted_words" in val.keys()): if val['snippet_highlighted_words']: print("mot_cles = " + str(val['snippet_highlighted_words'])) + ''' mydata['external_code'] = external_code_prefixe+"_"+str(cmpt) mydata['title'] = str(val['title']) mydata['url'] = str(val['link']) - mydata['description'] = str(val['snippet']) + + if ("snippet" in val.keys()): + if val['snippet']: + mydata['description'] = str(val['snippet']) if ("snippet_highlighted_words" in val.keys()): if val['snippet_highlighted_words']: mydata['tags'] = str(val['snippet_highlighted_words']) - mydata['update_daye'] = str(datetime.now()) - mydata['rang'] = str(val['position']) + mydata['update_date'] = str(datetime.now()) + + if ("position" in val.keys()): + if val['position']: + mydata['rang'] = str(val['position']) + mydata['orign_search_text'] = str(search_text) mydata['valide'] = "1" mydata['treated'] = "0" @@ -556,3 +579,48 @@ def RunSearchAPI(search_text=None, external_code_prefixe=None): mycommon.myprint(str(e) + " - Line : " + str(exc_tb.tb_lineno)) return False + + +''' +Cette fonction prends un mot, +et retourne sont masculin / singulier +Cette fonction va s'etoffer au fur et à mesure + +/!\ Cette fonction prend un pot, pas une phrase +''' +def GetMasculinSingulier(word=None): + try: + mot = str(word).lower() # mettre les mots en minuscule + # Retirons les caractères spéciaux : + + # mots terminés par "es" + patter2 = re.compile(r"\w+(ees)+$") + + # mots terminés par "s" + patter3 = re.compile(r"\w+(s)+$") + + # mots terminés par "x" + patter4 = re.compile(r"\w+(x)+$") + + + if (len(str(mot)) > 3): + if( re.match(patter2, str(mot))): + neword = mot[:-2] + return True, neword + + if (re.match(patter3, str(mot))): + neword = mot[:-1] + return True, neword + + if (re.match(patter4, str(mot))): + neword = mot[:-1] + return True, neword + + + return True, str(mot) + + + except Exception as e: + exc_type, exc_obj, exc_tb = sys.exc_info() + mycommon.myprint(str(e) + " - Line : " + str(exc_tb.tb_lineno)) + return False, "" diff --git a/test_perso.py b/test_perso.py new file mode 100644 index 0000000..2ab0b11 --- /dev/null +++ b/test_perso.py @@ -0,0 +1,117 @@ +import os +import csv +import inspect +import sys +from datetime import datetime +from pymongo import ReturnDocument +from unidecode import unidecode +import GlobalVariable as MYSY_GV +import prj_common as mycommon +import re +from pymongo import MongoClient +import pymongo + + +''' +Cette fonction essayer de faire une recherche de leveinstein +elle prend une liste mot : +pr chaque mot, +1 - elle prends les 3 premier caractère +2 - recherche ceux qui correspondent +3 - pour chaque mot trouvé, faire un distance de levein et voir + +puis elle retourne la liste des mots trouvé dans la table elaindex + +Regles fonctionnelles : +Si 0 < len(mot) <= 3 ==> Recherche strict à faire +Si 3 < len(mot) <= 5 ==> Recherche avec une distance de 1 +Si 5 < len(mot) <= 10 ==> Recherche avec une distance de 2 +Si 10 < len(mot) ==> Recherche avec une distance de 3 +''' + +def mysy_recherche_levenshtein_orig(): + try: + + coll_name = MYSY_GV.dbname['elaindex'] + mots = ['comptabilite', 'publique', 'fondamentau', 'programme', 'renforcement', 'defi', 'semaine', 'semaine'] + training_mots = [] + + + for mot in mots: + if( len( mot ) > 2): + mot_first_caract = mot[0:3] + #print(" Traitement de " + str(mot) + " = 3 first => " + str(mot_first_caract)) + + regx = re.compile("^" + mot_first_caract, re.IGNORECASE) + print("regx = " + str(regx)) + v = {'$regex': "^" + mot_first_caract} + print("v = " + str(v)) + + for x in coll_name.find({'mots': v}): + cmp_levenshtein = int(mycommon.levenshtein(mot, str(x['mots']))) + + + if( len(mot) <= 5 and cmp_levenshtein <= 1): + if( str(x['mots']) not in training_mots): + training_mots.append( str(x['mots']) ) + + elif( len(mot) <= 10 and cmp_levenshtein <= 2): + if( str(x['mots']) not in training_mots): + training_mots.append( str(x['mots']) ) + + elif ( cmp_levenshtein <= 3): + if (str(x['mots']) not in training_mots): + training_mots.append(str(x['mots'])) + + elif (cmp_levenshtein > 3): + print(" KOO cmp_levenshtein : "+mot+" CMP "+str(x['mots'])+" = "+str(cmp_levenshtein)+ + " ==> id_formation"+str(x['id_formation'])+" ==> occurrence = "+str(x['occurence'])) + + return True, training_mots + + except Exception as e: + exc_type, exc_obj, exc_tb = sys.exc_info() + mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno)) + return False, None + +def mysy_recherche_levenshtein(tab_mot): + try: + + coll_name = MYSY_GV.dbname['elaindex'] + training_mots = [] + + for mot in tab_mot: + if( len( mot ) > 2): + mot_first_caract = mot[0:3] + print(" Traitement de " + str(mot) + " = 3 first => " + str(mot_first_caract)) + + v = {'$regex': "^" + mot_first_caract} + print("v = " + str(v)) + + for x in coll_name.find({'mots': v}): + cmp_levenshtein = int(mycommon.levenshtein(mot, str(x['mots']))) + + + if( len(mot) <= 5 and cmp_levenshtein <= 1): + if( str(x['mots']) not in training_mots): + training_mots.append( str(x['mots']) ) + + elif( len(mot) <= 10 and cmp_levenshtein <= 2): + if( str(x['mots']) not in training_mots): + training_mots.append( str(x['mots']) ) + + elif ( cmp_levenshtein <= 3): + if (str(x['mots']) not in training_mots): + training_mots.append(str(x['mots'])) + + elif (cmp_levenshtein > 3): + print(" KOO cmp_levenshtein : " + mot + " CMP " + str(x['mots']) + " = " + str(cmp_levenshtein) + + " ==> id_formation" + str(x['id_formation']) + " ==> occurrence = " + str(x['occurence'])) + + + return True, training_mots + + except Exception as e: + exc_type, exc_obj, exc_tb = sys.exc_info() + mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno)) + return False, None