现在的位置: 首页 > 综合 > 正文

语言检测工具language-detection

2013年04月15日 ⁄ 综合 ⁄ 共 1337字 ⁄ 字号 评论关闭

给你一段文字,让你检测它是什么语言?有两个开源的项目可以使用。一个是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();
        }
        
    }

}

这段文字的检测结果是zh-cn,很简单。

 

language-detection基本的初始化工作都由DetectorFactory完成。检测前,需要先载入语言包(其实就是各个语言的样本,可以自行添加)。语言包最初是通过addProfile方法加入,其方法原型是addProfile(LangProfile profile, int index, int langsize),你可以构建自己的词汇表,然后通过addProfile方法添加。也可以使用loadProfile方法,把一个目录下的所有语言文件(按照要求的格式,下载的jar包有样例)一次性载入。后面就很简单了,通过DetectorFactory创建一个Detector,append需要检测的文字,detect一下,就返回语言类别,收工。

 

抱歉!评论已关闭.