算法之智能搜索(下)
阿新 • • 發佈:2018-11-25
substr list 詞語 bstr 智能搜索 amp param ant 沒有 以下內容,並未得到實質檢測。因為筆者沒有用到相關的需求,只是一時興起,按照自己的思路探究了一下。並未考慮什麽付費排名,詞語優先級,搜索量排名,時效性等等的因素。娛樂一下唄,可能會被真正做過此類搜索的大神笑話,擔待自己瞎想的。
二、簡單算法分詞匹配:
/**簡單算法之 * 拆分用戶輸入框輸入的語句,進行最大化匹配查詢 * @param str:用戶輸入的查詢內容 * Red_Ant 20181124 */ public static final String PUTUATION = "。,、':∶;?‘’“”〝〞?ˇ﹕︰﹔﹖﹑·¨….?;!′?!~—ˉ|‖"〃`@﹫??﹏﹋﹌︴々﹟#﹩$﹠&﹪%*﹡﹢﹦﹤‐ ̄ˉ―﹨??﹍﹎+=<--__-\\ˇ~﹉﹊()〈〉??﹛﹜『』〖〗[]《》〔〕{}「」【】︵︷︿︹︽_﹁﹃︻︶︸﹀︺︾ˉ﹂﹄︼"; public static List<String> dealInputStr(String str) { /*我們輸入內容進行查詢之後,總會有一些優先顯示在最前面(付費排名的除外) * 假設,查出的最終結果是String類型的 */ //1、創建存儲最終結果的集合 List<String> resultLst = new ArrayList<String>(); //2、優先級最高的就是,把用戶輸入的內容看做一個整體查出的內容 List<String> strLst = selectStrFromDataBase(str);//從相應的庫中查詢,內容。方法不同,此處略! if(strLst.size() > 0) { resultLst.addAll(strLst); } //3、接著我們利用,用戶輸入中的標點,將輸入語句分割成不同的str【以常用標點為例】 //筆者又想到,標點也有許多區別,和優先之分。算啦,不做深究了。 String[] strs = str.split(""); int strsLength = strs.length; List<Integer> num = new ArrayList<Integer>(); for (int i = 0; i < strsLength; i++) { if(PUTUATION.contains(strs[i])) { num.add(i); } } //將輸入語句,按照標點的位置進行分詞 int j = 0;//存儲截取字符串位置 /*用於存儲,標點分詞之後的結果 * 然後依照此結果進行細胞分詞 */ String ss; List<String> pttstrLst = new ArrayList<String>(); for (int i = 0; i < num.size(); i++) { if(i == num.size()-1) { ss = str.substring(j); }else { ss = str.substring(j, num.get(i)); } pttstrLst.add(ss); strLst = selectStrFromDataBase(ss); if(strLst.size() > 0) { resultLst.addAll(strLst); } j = num.get(i) + 1; } /*4、將標點分詞後的結果進行細胞分詞 * 利用字符字數逐步-1,的左右相鄰截取方式,將分詞後的內容,分別匹配細胞詞庫 * 每減少一n字,或有n+1種可能,直到只剩兩個字為止。 */ String ss1; for (int i = 0; i < pttstrLst.size(); i++) { //jugeWord(String str),查詢數據庫的方法略! ss = pttstrLst.get(i); int len = ss.length() - 2; int s = 0; int strlen = ss.length(); while (len > 1) { int len1 = strlen - 2; while (len1 < strlen-1) { ss1 = ss.substring(s, len1); if(!jugeWord(ss1)) { strLst = selectStrFromDataBase(ss1); if(strLst.size() > 0) { resultLst.addAll(strLst); } } s++; len1++; } len--; } } return resultLst; }
【註意】
以上方法並未在真實場景中的應用,還有許多未考慮的因素,筆者想若此方法行的通的話,還有許多值得考慮和優化的地方。
算法之智能搜索(下)