Canalblog
Editer l'article Suivre ce blog Administration + Créer mon blog
Publicité
LINUX & OPEN SOURCE
25 janvier 2009

SoundEx Anglais / Français

L'algorithme SoundEx permet de faire une recherche pseudo-phonétique. C'est un algorithme ancien qui donne beaucoup de trop de faux positifs, mais il a l'avantage d'être simple et rapide.  Je poste ici le code en c d'un soundex que j'ai trouvé sur le web. Je l'ai modifier pour qu'il accepte le codage anglais ou français et permette de définir la longueur de la clé. 

En rappel, le codage standard est une lettre en majuscule (la première du mot) et 3 chiffres décimaux.

Le code source est ici: soundex.c

#include <stdio.h>   
#include <string.h>
#include <ctype.h>

/*Entrer the string to convert and the length of the key to generate
* Standard is 4 => 1 letter + 3 digits*/
char *soundex(char *in,int lg,int lang) {
      static  int code[2][26] =
         {  0,1,2,3,0,1,2,0,0,2,2,4,5,5,0,1,2,6,2,3,0,1,0,2,0,2,  //en
            0,1,2,3,0,9,7,0,0,7,2,4,5,5,0,1,2,6,2,3,0,9,0,8,8,8 };//fr
         /* a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z */
         
      static char key[255]; //max 255 chars
      char ch;
      int last;
      int count;
   
      /*Initialise key*/
      key[0]='Z';
      for (count=1; count < lg; count++) key[count]='0';
      key[lg]='\0';

      /* Advance to the first letter.  If none present,
         return default key */
      while (*in != '\0'  &&  !isalpha(*in))
         ++in;
         if (*in == '\0') return(key);

      /* Pull out the first letter, uppercase it, and
         set up for main loop */
        key[0] = islower(*in) ? toupper(*in) : *in;
        last = code[lang][key[0] - 'A'];
        ++in;

      /* Scan rest of string, stop at end of string or
         when the key is full */
         for (count = 1;  count < lg  &&  *in != '\0';  ++in) {            
           /* If non-alpha, ignore the character altogether */
           if (isalpha(*in)) {
             ch = isupper(*in) ? tolower(*in) : *in;
             /* Fold together adjacent letters sharing the same code */
             if (last != code[lang][ch - 'a']) {
               last = code[lang][ch - 'a'];
               /* Ignore code==0 letters except as separators */
               if (last != 0) key[count++] = '0' + last;
             }
           }
         }

         return(key);
}

/* lets check the function */
int main() {
  char instring[80];
  int  length;
 
  printf("\nEnter the length of the key:");
  scanf("%i",&length);
  printf("\nEnter the string to convert (ctr-c to exit):");
  while (scanf("%80s",instring) != 0) {
    printf("English:%s\n", soundex(instring,length,0));
    printf("French :%s\n", soundex(instring,length,1));
  }
  return 0;
}

/*
Basic soundex - English and French
Prog found in the web and modified to accept none standard key length
- Modified JP Redonnet - 2008
*/

Publicité
Publicité
Commentaires
LINUX & OPEN SOURCE
Publicité
Archives
Publicité