crodas/languagedetector

简单的文本分类库

v0.1.1 2013-11-06 01:26 UTC

This package is auto-updated.

Last update: 2024-09-05 02:51:40 UTC


README

PHP 类,用于从任何自由文本中检测语言。

它遵循在这篇论文中描述的方法,给定文本被标记化成 N-Gram(在此步骤之前我们会清理空白字符)。然后我们对 tokens 进行排序,并与语言 模型 进行比较。

工作原理

我们首先需要一个 语言模型(看起来像 这个文件),在分类时间用来比较文本。这个过程必须在 之前 进行,并且可以使用类似于 这个文件 的脚本生成。

// register the autoloader
require 'lib/LanguageDetector/autoload.php';

// it could use a little bit of memory, but it's fine
// because this process runs once.
ini_set('memory_limit', '1G');

// we load the configuration (which will be serialized
// later into our language model file
$config = new LanguageDetector\Config;

$c = new LanguageDetector\Learn($config);
foreach (glob(__DIR__ . '/samples/*') as $file) { 
    // feed with examples ('language', 'text');
    $c->addSample(basename($file), file_get_contents($file));
}

// some callback so we know where the process is 
$c->addStepCallback(function($lang, $status) {
    echo "Learning {$lang}: $status\n";
});

// save it in `datafile`. 
// we currently support the `php` serialization but it's trivial
// to add other formats, just extend `\LanguageDetector\Format\AbstractFormat`. 
//You can check example at https://github.com/crodas/LanguageDetector/blob/master/lib/LanguageDetector/Format/PHP.php
$c->save(AbstractFormat::initFormatByPath('language.php'));

一旦我们有了语言模型文件(在这种情况下 language.php),我们就可以根据语言对文本进行分类了。

// register the autoloader
require 'lib/LanguageDetector/autoload.php';

// we load the language model, it would create
// the $config object for us.
$detect = LanguageDetector\Detect::initByPath('language.php');

$lang = $detect->detect("Agricultura (-ae, f.), sensu latissimo, 
est summa omnium artium et scientiarum et technologiarum quae de 
terris colendis et animalibus creandis curant, ut poma, frumenta, 
charas, carnes, textilia, et aliae res e terra bene producantur. 
Specialius, agronomia est ars et scientia quae terris colendis student, 
agricultio autem animalibus creandis.")

var_dump($lang);

就是这样。

算法

该项目设计为与模块一起工作,这意味着你可以提供自己的算法来对 N-Gram 进行 排序比较。默认情况下,库实现 PageRank 作为排序算法,以及 原地(在论文中描述)作为比较。

为了提供自己的算法,你必须在 学习阶段 改变 $config 来加载自己的类(顺便说一句,这些类应该实现一些接口)。