drupol / phpngrams
从字符串和/或数组中获取 N-Grams。
1.1.3
2019-07-24 06:42 UTC
Requires
- php: >= 7.1.3
- drupol/phpermutations: ^1
Requires (Dev)
- drupol/php-conventions: ^1.5
- drupol/phpspec-code-coverage: ^5.0
- phpspec/phpspec: ^5.1
- scrutinizer/ocular: ^1
README
PHPNgrams
PHP N-Grams 库
介绍
在计算语言学、机器学习和概率论领域,n-gram 是从给定文本或语音样本中连续的 n 个项的序列。这些项可以是音素、音节、字母、单词或碱基对,具体取决于应用。n-gram 通常是从文本或语音语料库中收集的。当项是单词时,n-gram 也可能被称为 shingles。
大小为 1 的 n-gram 称为“unigram”;大小为 2 的称为“bigram”(或较少见的“digram”);大小为 3 的称为“trigram”。较大的大小有时用 n 的值来表示,例如“four-gram”、“five-gram”等。(更多请参考 维基百科)
要求
- PHP >= 7.0
安装
通过以下操作将此库包含到您的项目中
composer require drupol/phpngrams
此库提供两个类
- NGrams
- NGramsCyclic
以及一个特质
- NGramsTrait
用法
<?php declare(strict_types = 1); namespace drupol\phpngrams\tests; use drupol\phpngrams\NGrams; use drupol\phpngrams\NGramsCyclic; include 'vendor/autoload.php'; $string = 'hello world'; // Better use preg_split() than str_split() in case of UTF8 strings. $chars = preg_split('/(?!^)(?=.)/u', $string); $ngrams = (new NGrams())->ngrams($chars, 3); print_r(iterator_to_array($ngrams)); /* [ 0 => [ 0 => 'h', 1 => 'e', 2 => 'l', ], 1 => [ 0 => 'e', 1 => 'l', 2 => 'l', ], 2 => [ 0 => 'l', 1 => 'l', 2 => 'o', ], 3 => [ 0 => 'l', 1 => 'o', 2 => ' ', ], 4 => [ 0 => 'o', 1 => ' ', 2 => 'w', ], 5 => [ 0 => ' ', 1 => 'w', 2 => 'o', ], 6 => [ 0 => 'w', 1 => 'o', 2 => 'r', ], 7 => [ 0 => 'o', 1 => 'r', 2 => 'l', ], 8 => [ 0 => 'r', 1 => 'l', 2 => 'd', ], ]; */ $string = 'hello world'; // Better use preg_split() than str_split() in case of UTF8 strings. $chars = preg_split('/(?!^)(?=.)/u', $string); $ngrams = (new NGramsCyclic())->ngrams($chars, 3); print_r(iterator_to_array($ngrams)); /* [ 0 => [ 0 => 'h', 1 => 'e', 2 => 'l', ], 1 => [ 0 => 'e', 1 => 'l', 2 => 'l', ], 2 => [ 0 => 'l', 1 => 'l', 2 => 'o', ], 3 => [ 0 => 'l', 1 => 'o', 2 => ' ', ], 4 => [ 0 => 'o', 1 => ' ', 2 => 'w', ], 5 => [ 0 => ' ', 1 => 'w', 2 => 'o', ], 6 => [ 0 => 'w', 1 => 'o', 2 => 'r', ], 7 => [ 0 => 'o', 1 => 'r', 2 => 'l', ], 8 => [ 0 => 'r', 1 => 'l', 2 => 'd', ], 9 => [ 0 => 'l', 1 => 'd', 2 => 'h', ], 10 => [ 0 => 'd', 1 => 'h', 2 => 'e', ], ]; */
为了最大限度地减少内存占用,该库返回生成器。如果您想获取完整的结果数组,请使用 iterator_to_array()。
API
完整的 API 文档可以在 https://not-a-number.io/phpngrams 找到。
代码质量和测试
每当向库中引入更改时,Travis CI 会运行测试。
该库使用 PHPSpec 编写测试。
请自由地检查 spec
目录中的它们。运行 composer phpspec
以触发测试。
PHPInfection 用于确保您的代码得到适当测试,运行 composer infection
以测试您的代码。
贡献
请自由地通过发送 Github pull 请求来为此库做出贡献。我反应很快:-)