惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

GbyAI
GbyAI
WordPress大学
WordPress大学
D
DataBreaches.Net
腾讯CDC
小众软件
小众软件
B
Blog RSS Feed
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
The Blog of Author Tim Ferriss
MongoDB | Blog
MongoDB | Blog
U
Unit 42
Y
Y Combinator Blog
V
V2EX
I
InfoQ
D
Docker
量子位
N
Netflix TechBlog - Medium
Recent Announcements
Recent Announcements
A
About on SuperTechFans
博客园 - 叶小钗
大猫的无限游戏
大猫的无限游戏
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
B
Blog
阮一峰的网络日志
阮一峰的网络日志
MyScale Blog
MyScale Blog

博客园 - Bryan Wong

Pushlets的初始化陷阱 在Tomcat部署Solr 4.3 Spring Security如何防止会话固定攻击(session fixation attack) Jdk自带的定时任务TimerTask和ScheduledExecutorService及其在Spring中的集成 Lucene索引,查询及高亮显示 记录几个Json的lib 蛋疼的腾讯微博数据类型和API文档 你所不知道的Quartz特性 Spring Data集成MongoDB访问 Jetty的jar包依赖关系图 CAPS & BHCA Java中的集合类图 下载SUSE Linux 10 sp1的经历好曲折 C#代码检查工具:stylecop 圈复杂度基础 Scrum——“鸡”和“猪”的寓言 使用java断言调测程序 无所不能的final关键字 不同于C#的Java值类型和String类型
语言检测工具language-detection
Bryan Wong · 2012-09-26 · via 博客园 - Bryan Wong

给你一段文字,让你检测它是什么语言?有两个开源的项目可以使用。一个是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一下,就返回语言类别,收工。