java 簡單的模糊查找


最近做一個基於語音的文件管理器,說幾個字就可以找到相應的文件或者歌曲,視頻等

當語音輸入的,在文件中找不到完全匹配時,進行模糊查找,找到相似度最高的並且打開它。

  1.      File File1=new File("/sdcard/music");    主函數的一部分
  2.      serchFile(File1);                                 查找
  3.      if(max==0) Toast.makeText(FileManager.this, "沒有找到", Toast.LENGTH_LONG).show();   報錯
  4.      else openFile(maxfile);                        打開找到的匹配度最高的那一個文件
  5.     String Keywords="彩虹.mp3";     這是需要搜索的歌曲  屬於外部輸入
  6.     File maxfile = new File("/");         用於保存匹配度最高的文件
  7.     int max = 0;                             保存匹配值 用於比較
  8.     private void serchFile(File file){
  9.             if(file.canRead()){//只能遍歷可讀的文件夾,否則會報錯
  10.                 File[] mFileArray = file.listFiles();      file文件路徑下的所有文件都放在這個文件數組中
  11.                 for(File currentArray:mFileArray){
  12.                     if(currentArray.exists()&&currentArray.isDirectory()){//如果是文件夾則回調該方法
  13.                         serchFile(currentArray);          如果是文件夾  回調serchFile函數             
  14.                     }
  15.                     else {                                       如果不是  就進行比較  匹配值為當前最高時修改max  maxfile變量
  16.                         for(int j=0;j<mFileArray.length;j++){
  17.                             if(this.contrast(Keywords,mFileArray[j].getName())>max){
  18.                                 max = this.contrast(Keywords,mFileArray[j].getName());
  19.                                 maxfile = mFileArray[j];
  20.                             }
  21.                         }
  22.                     }
  23.                 }   
  24.              }
  25.     }
  26.     private int contrast(String str1,String str2){    具體對比實現
  27.         int a=0;
  28.         int k=0;
  29.         char[] chars1=str1.toCharArray();     字符串轉換為字符數組  java使用UTF-8編碼格式存儲  使用的時候如果帶有漢字則都為16位  非常方便
  30.         char[] chars2=str2.toCharArray();
  31.         for(int i=0;i<chars1.length;i++){       一個一個的對比
  32.             for(int j=0;j<chars2.length-k;j++){
  33.                 if(chars1[i]==chars2[j]){
  34.                     a++;
  35.                     for(;(j+1)<chars2.length-k;j++){    為防止漢字的重復出現  進行刪減字符數組
  36.                         chars2[j]=chars2[j+1];
  37.                     }
  38.                     k++;
  39.                 }
  40.             }
  41.         }
  42.         return a;    最后返回匹配值
  43.     }
  44. 以上為簡單的實現  不能對漢字單詞進行識別  很遺憾


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM