標籤:apache java code 原始碼
Apache commons codec的language是一個功能比較強大的包,主要是用在對各種語言的處理上,當然,這個包對漢字的支援很糟糕。這一塊的內容,在網上非常少,只能自己寫一些挺膚淺的代碼,以後如果有機會接觸,再完善。
我們先學習下編碼的範例。
Examples of Soundex Coding |
Name Letters Coded Coding |
Allricht l, r, c A-462 |
Eberhard b, r, r E-166 |
Engebrethson n, g, b E-521 |
Heimbach m, b, c H-512 |
Hanselmann n, s, l H-524 |
Henzelmann n, z, l H-524 |
Hildebrand l, d, b H-431 |
Kavanagh v, n, g K-152 |
Lind, Van n, d L-530 |
Lukaschowsky k, s, s L-222 |
McDonnell c, d, n M-235 |
McGee c M-200 |
O‘Brien b, r, n O-165 |
Opnian p, n, n O-155 |
Oppenheimer p, n, m O-155 |
Swhgler s, l, r S-460 |
Riedemanas d, m, n R-355 |
Zita t Z-300 |
Zitzmeinn t, z, m Z-325 |
在一些英文使用的場合中,特別是語音上,有很多可能相似的單詞,用這個包裡的方法使用下:
package test.ffm83.commons.codec;
import org.apache.commons.codec.language.RefinedSoundex;
import org.apache.commons.lang.StringUtils;
/**
* 通過apache commonscodec的lanauage包進行字元的相似度差異
* 返回的是0到最短的編碼長度,0表示無關,4或者意味著可能比較相似
* @author範芳銘
*/
public classEasyLanguageDiff {
private RefinedSoundexstringEncoder = this.createStringEncoder();
public static void main(String[] args)throws Exception{
EasyLanguageDiffdiff = newEasyLanguageDiff();
diff.getDifference();
diff.getEncode();
}
protectedRefinedSoundex createStringEncoder() {
return new RefinedSoundex();
}
publicRefinedSoundex getStringEncoder() {
return this.stringEncoder;
}
public void getDifference() throws Exception{
System.out.println(StringUtils.center("字串差異", 50,"-"));
System.out.println(this.getStringEncoder().difference(null,null));
System.out.println(this.getStringEncoder().difference("",""));
System.out.println(this.getStringEncoder().difference(" "," "));
System.out.println(this.getStringEncoder().difference("Margaret","Andrew"));
System.out.println(this.getStringEncoder().difference("Smith","Smythe"));
System.out.println(this.getStringEncoder().difference("Ann","Andrew"));
System.out.println(this.getStringEncoder().difference("Green","Greene"));
System.out.println(this.getStringEncoder().difference("Smithers","Smythers"));
System.out.println();
}
public void getEncode() throws Exception{
System.out.println(StringUtils.center("語言編碼", 50,"-"));
System.out.println(this.getStringEncoder().encode("testing"));
System.out.println(this.getStringEncoder().encode("TESTING"));
System.out.println(this.getStringEncoder().encode("dogs"));
System.out.println(RefinedSoundex.US_ENGLISH.encode("dogs"));
//目前不支援漢字,加入就直接異常
//System.out.println(this.getStringEncoder().encode("範芳銘"));
System.out.println();
}
}
運行結果如下:
----------------------字串差異-----------------------
0
0
0
1
6
3
5
8
-----------------------語言編碼-----------------------
T6036084
T6036084
D6043
D6043
Apache commons codec 之language