給你一段文字,讓你檢測它是什么語言?有兩個開源的項目可以使用。一個是Apache Tika,一個是language-detection。language-detection是google Code上開源的一個語言檢測軟件包,不折不扣的日貨,但使用起來非常方便,其project鏈接如下:http://code.google.com/p/language-detection。基本上,你只需要引用langdetect.jar和其依賴的jsonic-1.3.0.jar(也是日貨)即可,下面是一個簡單的例子。
新建一個Java工程,將上述兩個jar包引入工程,新建一個測試類,如下:
import java.net.URISyntaxException;
import com.cybozu.labs.langdetect.*;
/**
* @author XXX
*
*/
public class LangTest
{
/**
* @param args
*/
public static void main(String[] args)
{
try
{
DetectorFactory.loadProfile(Thread.currentThread().getContextClassLoader().getResource("lang").getPath());
} catch (LangDetectException e)
{
e.printStackTrace();
}
Detector detect;
try
{
detect = DetectorFactory.create();
detect.append("我靠a靠靠靠a");
System.out.println(detect.detect());
} catch (LangDetectException e)
{
e.printStackTrace();
}
}
}
import com.cybozu.labs.langdetect.*;
/**
* @author XXX
*
*/
public class LangTest
{
/**
* @param args
*/
public static void main(String[] args)
{
try
{
DetectorFactory.loadProfile(Thread.currentThread().getContextClassLoader().getResource("lang").getPath());
} catch (LangDetectException e)
{
e.printStackTrace();
}
Detector detect;
try
{
detect = DetectorFactory.create();
detect.append("我靠a靠靠靠a");
System.out.println(detect.detect());
} catch (LangDetectException e)
{
e.printStackTrace();
}
}
}
這段文字的檢測結果是zh-cn,很簡單。
language-detection基本的初始化工作都由DetectorFactory完成。檢測前,需要先載入語言包(其實就是各個語言的樣本,可以自行添加)。語言包最初是通過addProfile方法加入,其方法原型是addProfile(LangProfile profile, int index, int langsize),你可以構建自己的詞匯表,然后通過addProfile方法添加。也可以使用loadProfile方法,把一個目錄下的所有語言文件(按照要求的格式,下載的jar包有樣例)一次性載入。后面就很簡單了,通過DetectorFactory創建一個Detector,append需要檢測的文字,detect一下,就返回語言類別,收工。