IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

 C Discussion :

Distance d'édition: écriture


Sujet :

C

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Inscrit en
    Juillet 2005
    Messages
    49
    Détails du profil
    Informations forums :
    Inscription : Juillet 2005
    Messages : 49
    Par défaut Distance d'édition: écriture
    Bonjour,

    mon objectif est le calcul de distances d'édition dans le cas de l'ecriture. J'ai téléchargé et modifié légèrement le code suivant. Mais à l'exécution, le programme ne tient pas compte de mon dictionnaire lexical, et juge que tous les mots que j'écris sont corrects, ce qui n'est pas vrai. Le programme doit comparer chaque mot que j'écrit avec tous les mots du dictionnaire, et calculer les distances d'édition à chaque fois.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    /* 
     * spell.c --- spell corrector
     * 
     * Copyright  (C)  2007  Marcelo Toledo <marcelo@marcelotoledo.org>
    */
     
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    #include <search.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <unistd.h>
     
    //#define DICTIONARY "./big.txt"
    #define DICTIONARY "./DICO_1129.txt"
    #define DICT_SZ    3000000
     
    const char delim[]    = ".,:;`/\"+-_(){}[]<>*&^%$#@!?~/|\\=1234567890 \t\n";
    const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
     
    static char *strtolower(char *word)
    {
            char *s;
     
            for (s = word; *s; s++)
                    *s = tolower(*s);
     
            return word;
    }
     
    static ENTRY *find(char *word)
    {
            ENTRY e;
     
            e.key = word;
            return hsearch(e, FIND);
    }
     
    static int update(char *word)
    {
            ENTRY *e = find(word);
     
            if (!e)
                    return 0;
     
            e->data++;
     
            return 1;
    }
     
    static int read_file(ENTRY dict)
    {
            char *file, *word, *w;
            FILE *fp = fopen(DICTIONARY, "r");
            struct stat sb;
     
            if (!fp)
                    return 0;
     
            if (stat(DICTIONARY, &sb))
                    return 0;
     
            file = malloc(sb.st_size);
            if (!file) {
                    fclose(fp);
                    return 0;
            }
     
            fread(file, sizeof(char), sb.st_size, fp);
     
            word = strtok(file, delim);
            while(word != NULL) {
                    w = strtolower(strdup(word));
     
                    if (!update(w)) {
                            dict.key  = w;
                            dict.data = 0;
                            hsearch(dict, ENTER);
                    }
     
                    word = strtok(NULL, delim);
            }
     
            free(file);
            fclose(fp);
     
            return 1;
    }
     
    static char *substr(char *str, int offset, int limit)
    {
            char *new_str;
            int str_size = strlen(str);
     
            if ((limit > str_size) || ((offset + limit) > str_size) || 
                (str_size < 1) || (limit == 0))
                    return NULL;
     
            new_str = malloc(limit+1 * sizeof(char));
            if (!new_str)
                    return NULL;
     
            strncpy(new_str, str+offset, limit);
            *(new_str + limit) = '\0';
     
            return new_str;
    }
     
    static char *concat(char *str1, char *str2)
    {
            if (!str1) { 
                    str1 = malloc(sizeof(char));
                    *str1 = '\0';
            }
     
            if (!str2) { 
                    str2 = malloc(sizeof(char));
                    *str2 = '\0';
            }
     
            str1 = realloc(str1, strlen(str1) + strlen(str2) + 1);
            return strcat(str1, str2);
    }
     
    static int deletion(char *word, char **array, int start_idx)
    {
            int i, word_len = strlen(word);
     
            for (i = 0; i < word_len; i++)
                    array[i + start_idx] = concat(substr(word, 0, i), substr(word, i+1, word_len-(i+1)));
     
            return i;
    }
     
    static int transposition(char *word, char **array, int start_idx)
    {
            int i, word_len = strlen(word);
     
            for (i = 0; i < word_len-1; i++)
                    array[i + start_idx] = concat(concat(substr(word, 0, i), 
                                                         substr(word, i+1, 1)), 
                                                  concat(substr(word, i, 1), 
                                                         substr(word, i+2, word_len-(i+2))));
     
            return i;
    }
     
    static int alteration(char *word, char **array, int start_idx)
    {
            int i, j, k, word_len = strlen(word);
            char c[2] = { 0, 0 };
     
            for (i = 0, k = 0; i < word_len; i++)
                    for (j = 0; j < sizeof(alphabet); j++, k++) {
                            c[0] = alphabet[j];
                            array[start_idx + k] = concat(concat(substr(word, 0, i), (char *) &c), 
                                                          substr(word, i+1, word_len - (i+1)));
                    }
     
            return k;
    }
     
    static int insertion(char *word, char **array, int start_idx)
    {
            int i, j, k, word_len = strlen(word);
            char c[2] = { 0, 0 };
     
            for (i = 0, k = 0; i <= word_len; i++)
                    for (j = 0; j < sizeof(alphabet); j++, k++) {
                            c[0] = alphabet[j];
                            array[start_idx + k] = concat(concat(substr(word, 0, i), (char *) &c), 
                                                          substr(word, i, word_len - i));
                    }
     
            return k;
    }
     
    static int edits1_rows(char *word)
    {
            register int size = strlen(word);
     
            return (size)                          + // deletion
                   (size - 1)                      + // transposition
                   (size * sizeof(alphabet))       + // alteration
                   (size + 1) * sizeof(alphabet);    // insertion
    }
     
    static char **edits1(char *word)
    {
            int next_idx;
            char **array = malloc(edits1_rows(word) * sizeof(char *));
     
            if (!array)
                    return NULL;
     
            next_idx  = deletion(word, array, 0);
            next_idx += transposition(word, array, next_idx);
            next_idx += alteration(word, array, next_idx);
            insertion(word, array, next_idx);
     
            return array;
    }
     
    static int array_exist(char **array, int rows, char *word)
    {
            int i;
     
            for (i = 0; i < rows; i++)
                    if (!strcmp(array[i], word))
                            return 1;
     
            return 0;
    }
     
    static char **known_edits2(char **array, int rows, int *e2_rows)
    {
            int i, j, res_size, e1_rows;
            char **res = NULL, **e1;
     
            for (i = 0, res_size = 0; i < rows; i++) {
                    e1      = edits1(array[i]);
                    e1_rows = edits1_rows(array[i]);
     
                    for (j = 0; j < e1_rows; j++)
                            if (find(e1[j]) && !array_exist(res, res_size, e1[j])) {
                                    res             = realloc(res, sizeof(char *) * (res_size + 1));
                                    res[res_size++] = e1[j];
                            }
            }
     
            *e2_rows = res_size;
     
            return res;
    }
     
    static char *max(char **array, int rows)
    {
            char *max_word = NULL;
            int i, max_size = 0;
            ENTRY *e;
     
            for (i = 0; i < rows; i++) {
                    e = find(array[i]);
                    if (e && ((int) e->data > max_size)) {
                            max_size = (int) e->data;
                            max_word = e->key;
                    }
            }
     
            return max_word;
    }
     
    static void array_cleanup(char **array, int rows)
    {
            int i;
     
            for (i = 0; i < rows; i++)
                    free(array[i]);
    }
     
    static char *correct(char *word)
    {
            char **e1, **e2, *e1_word, *e2_word, *res_word = word;
            int e1_rows, e2_rows;
     
            if (find(word))
                    return word;
     
            e1_rows = edits1_rows(word);
            if (e1_rows) {
                    e1      = edits1(word);
                    e1_word = max(e1, e1_rows);
     
                    if (e1_word) {
                            array_cleanup(e1, e1_rows);
                            free(e1);
                            return e1_word;
                    }
            }
     
            e2 = known_edits2(e1, e1_rows, &e2_rows);
            if (e2_rows) {
                    e2_word = max(e2, e2_rows);
                    if (e2_word)
                            res_word = e2_word;
            }
     
            array_cleanup(e1, e1_rows);
            array_cleanup(e2, e2_rows);
     
            free(e1);
            free(e2);
     
            return res_word;
    }
     
    int main(int argc, char **argv)
    {
            char *corrected_word;
            ENTRY dict;
     
            hcreate(DICT_SZ);
     
            if (!read_file(dict))
                    return -1;
     
            corrected_word = correct(argv[1]);
            if (strcmp(corrected_word, argv[1])) {
                    printf("Did you mean \"%s\"?\n", corrected_word);
            } else {
                    printf("\"%s\" is correct!\n", argv[1]);
            }
            return 0;
     
            //system ("pause");
    }

  2. #2
    Invité(e)
    Invité(e)
    Par défaut
    Bonjour,

    le problème vient à mon avis de l'initialisation de res_word dans la fonction correct.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    static char *correct(char *word)
    {
            char **e1, **e2, *e1_word, *e2_word, *res_word = word;
    il aurait fallu écrire :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    static char *correct(char *word)
    {
            char **e1, **e2, *e1_word, *e2_word, *res_word = "";
    Avec un dico ne contenant que le mot chien
    Avant :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    >./a.exe niche
    "niche" is correct!
    Après :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    >./a.exe niche
    Did you mean ""?
     
    >./a.exe chien
    "chien" is correct!
    Au passage, si le dico est absent, le programme quitte sans explication, c'est génant...

  3. #3
    Membre averti
    Inscrit en
    Juillet 2005
    Messages
    49
    Détails du profil
    Informations forums :
    Inscription : Juillet 2005
    Messages : 49
    Par défaut
    Bonjour Mabu, merci pour ta réponse.

    Le problème demeure inchangé: j'ai toujours "correct", que le mot soit vrai ou faux.

  4. #4
    Expert confirmé

    Profil pro
    Inscrit en
    Janvier 2007
    Messages
    10 610
    Détails du profil
    Informations personnelles :
    Âge : 67
    Localisation : France

    Informations forums :
    Inscription : Janvier 2007
    Messages : 10 610
    Billets dans le blog
    2
    Par défaut
    Primo, ça sent le "hacker" et l'obfuscation...

    Pas d'initialisation des pointeurs.
    Sous-entendus pour faire court dans l'écriture et qui n'apportent rien, au contraire..

    (exemple :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
            for (s = word; *s; s++)
    est une horreur...

    Je pense que l'erreur vient de :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
                    w = strtolower(strdup(word));
    ce devrait être :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    w = strdup(word);
    w = strtolower(w);
    Peut-être.....

    Mais le code est tellement mal fait que je ne regarderais pas plus...

  5. #5
    Expert éminent
    Avatar de Médinoc
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Septembre 2005
    Messages
    27 395
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Septembre 2005
    Messages : 27 395
    Par défaut
    On peut rajouter à cela l'absence de const, et l'abus de int là où des size_t sont plus appropriés (des tas de warnings 64 bits sous Visual)...

    Mais au moins il n'y a pas de cast de malloc().
    SVP, pas de questions techniques par MP. Surtout si je ne vous ai jamais parlé avant.

    "Aw, come on, who would be so stupid as to insert a cast to make an error go away without actually fixing the error?"
    Apparently everyone.
    -- Raymond Chen.
    Traduction obligatoire: "Oh, voyons, qui serait assez stupide pour mettre un cast pour faire disparaitre un message d'erreur sans vraiment corriger l'erreur?" - Apparemment, tout le monde. -- Raymond Chen.

  6. #6
    Expert confirmé

    Profil pro
    Inscrit en
    Janvier 2007
    Messages
    10 610
    Détails du profil
    Informations personnelles :
    Âge : 67
    Localisation : France

    Informations forums :
    Inscription : Janvier 2007
    Messages : 10 610
    Billets dans le blog
    2
    Par défaut
    Citation Envoyé par Médinoc Voir le message
    Mais au moins il n'y a pas de cast de malloc().
    on ne rentrera pas dans ce débat

    Mais le code est typiquement ce qui se fait d'ultra mauvais dans l'Open Source... ou le freeware...

  7. #7
    Expert confirmé

    Profil pro
    Inscrit en
    Janvier 2007
    Messages
    10 610
    Détails du profil
    Informations personnelles :
    Âge : 67
    Localisation : France

    Informations forums :
    Inscription : Janvier 2007
    Messages : 10 610
    Billets dans le blog
    2
    Par défaut
    Bpn j'ai regardé...

    C'est une vraie hooreur de partout.. SURTOUT A NE PAS SUIVRE...

    FILE*, char *, en général tous les pointeurs sont pris pour des booléens.. Qu'est-ce que ça coûte de tester réellement par rapport à leur valeur de retour (NULL, ou des 0, etc..) ??

    En fait, le problème est là où l'a dit mabu.. MAis pour bien départager il fau assigner à NULL.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    static char *correct(char *word)
    {
            char **e1, **e2, *e1_word, *e2_word, *res_word = NULL;
    Et rajouter dans le main :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
            if ( (mot_corrige = correct(argv[1])) == NULL )
            { 
               printf("Mot inconnu !!\n");
            }
            else
            if (strcmp(argv[1], mot_corrige)) {
                    printf("Vouliez-voud dire \"%s\"?\n", mot_corrige);
            } else {
                    printf("\"%s\" est correct!\n", argv[1]);
            }

  8. #8
    Membre averti
    Inscrit en
    Juillet 2005
    Messages
    49
    Détails du profil
    Informations forums :
    Inscription : Juillet 2005
    Messages : 49
    Par défaut
    Bonsoir, merci.
    J'obtiens l'erreur suivante à l'exécution:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    Program received signal SIGSEGV, Segmentation fault.
    0xb7ed9113 in strlen () from /lib/libc.so.6
    (gdb) Quit
    (gdb) bt
    #0  0xb7ed9113 in strlen () from /lib/libc.so.6
    #1  0xb7f2a3d8 in hsearch_r () from /lib/libc.so.6
    #2  0xb7f2a39c in hsearch () from /lib/libc.so.6
    #3  0x0804876a in find (mot=0x0) at correctionEcriture.c:35
    #4  0x0804903e in correct (mot=0x0) at correctionEcriture.c:267
    #5  0x08049146 in main (argc=1, argv=0xbf9c90d4) at correctionEcriture.c:353
    J'ai une erreur de segmentation liée à fonction strlen() incluse dans la fonction hsearch.

  9. #9
    Expert confirmé

    Profil pro
    Inscrit en
    Janvier 2007
    Messages
    10 610
    Détails du profil
    Informations personnelles :
    Âge : 67
    Localisation : France

    Informations forums :
    Inscription : Janvier 2007
    Messages : 10 610
    Billets dans le blog
    2
    Par défaut
    Citation Envoyé par tonguim Voir le message
    Bonsoir, merci.
    J'obtiens l'erreur suivante à l'exécution:
    .
    J'ai une erreur de segmentation liée à fonction strlen() incluse dans la fonction hsearch.
    Tu as dû faire autre chose..

    Le res_word est affecté à la fin, et n'est pas utilisé dans find....

Discussions similaires

  1. Comment calculer la distance d'édition ?
    Par AYDIWALID dans le forum OpenCV
    Réponses: 2
    Dernier message: 08/03/2012, 15h59
  2. [PHP 4] [FTP] Écriture dans un fichier à distance
    Par jules_diedhiou dans le forum Langage
    Réponses: 7
    Dernier message: 27/03/2009, 22h00
  3. executer une application a distance : Sockets ? RPC ? CORBA?
    Par a_hic dans le forum Développement
    Réponses: 5
    Dernier message: 30/05/2006, 13h02
  4. Réponses: 2
    Dernier message: 06/07/2002, 12h36
  5. Réponses: 3
    Dernier message: 07/05/2002, 16h06

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo