Text to keywords php

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

This library provides PHP functions to extract keywords from HTML and text

hugsbrugs/php-keywords

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

readme.md

This library provides PHP functions to extract keywords from HTML and text. Read PHP DOC

Install package with composer

composer require hugsbrugs/php-keywords 

In your PHP code, load librairy

require_once __DIR__ . '/vendor/autoload.php'; use Hug\Keywords\Keywords as Keywords;

If you have HTML as input, first extract text from HTML (it also returns Title and meta description)

$text = Keywords::get_text_from_html($html);

Then call the Keyword class with text as only required parameter. In this case the library patrickschur/language-detection will be used to automatically detect language.

$Keywords = new Keywords($text); $kws = $Keywords->keywords;

If you know which language is used in your text, then pass parameter lang as second argument. It will allow to load stop words list from voku/stop-words library. Supported languages codes by this library are : ar, bg, ca, cz, da, de, el, en, eo, es, et, fi, fr, hi, hr, hu, id, it, ka, lt, lv, nl, no, pl, pt, ro, ru, sk, sv, tr, uk, vi.

$Keywords = new Keywords($text, $lang); $kws = $Keywords->keywords;

If your language is not supported by voku/stop-words library or if you want to use your own stop words list, set 2nd argument as null and pass your own stop words array as 3rd argument.

$Keywords = new Keywords($text, 'auto', ['my custom stop word array']); $kws = $Keywords->keywords;

You can optionnaly pass a 4th argument as the max numbers of keywords to be returned. Set to 20 by default. Pass 0 if you want all keywords. In all cases it only returns keywords with occurence above 1.

$Keywords = new Keywords($text, 'fr', [], 10); $kws = $Keywords->keywords;

You can also pass an optionnal 5th argument array containing a list of chars you want to be removed from the analysed text. The default list is : | / & : , ; ! ? _ * — — . → – « » + ✔ # ¿ < >[ ]

$Keywords = new Keywords($text, 'fr', [], 10, ['my custom chars list']); $kws = $Keywords->keywords;

The optionnal 6th argument represents minimum keyword occurence to be returned. Default value is set to 2 so only keywords with minimum 2 occurences will be returned. If you want to get all keywords including those with only 1 occurence, set this parameter to 1.

$Keywords = new Keywords($text, 'fr', [], 10, ['my custom chars list'], 1); $kws = $Keywords->keywords;

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

extract relevant keywords from a given text

License

crodas/TextRank

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

extract relevant keywords from a given text

In order to use the class, you must instance a Config object.

 require __DIR__ . "/vendor/autoload.php"; use \crodas\TextRank\Config; use \crodas\TextRank\TextRank; $config = new Config; $textrank = new TextRank($config); $keywords = $textrank->getKeywords($some_long_text); var_dump($keywords);

It is possible to get better results by adding few information about the language ( stopword list, stemmer with pecl install stem ).

 require __DIR__ . "/vendor/autoload.php"; use \crodas\TextRank\Config; use \crodas\TextRank\TextRank; use \crodas\TextRank\Stopword; $config = new Config; $config->addListener(new Stopword); $textrank = new TextRank($config); $keywords = $textrank->getKeywords($some_long_text); var_dump($keywords);

By doing this it will detect the language of the text and will remove common words (from the stopword list). If ext-stem is available the results will be even better.

This class is also capable of summarizing long texts

$config = new \crodas\TextRank\Config; $config->addListener(new \crodas\TextRank\Stopword); $analizer = new \crodas\TextRank\Summary($config); $summary = $analizer->getSummary($text);

$summary is at most 5% of the sentences of the text.

Источник

PHP. Автоматическая генерация ключевых слов для сайта

Данный материал предоставлен сайтом PacificSky.Ru исключительно в ознакомительных целях. Администрация не несет ответственности за его содержимое.

В данной статье рассмотрен пример реализации кода, для автоматической генерации ключевых слов на основании текста статьи.
Допустим вы реализуете сбой (блог, cms и тд). И вам захотелось автоматически генерировать ключевые слова для своего контента.
Если это так, то данная статья вам будет интересна.

В статье будет приведен пример в котором будут отбираться ключевые слова .
Слова буду отбираться на основании повторения их в тексте статьи.
Проще говоря. У нас есть текст произвольной длины. Мы будем собирать все слова содержащиеся в тексте и подсчитывать количество их повторений.
Чем чаще будут повторяться слова, тем выше они будут выдаваться в массиве ключевых слов. Мы можем делать отбор слов по частоте их повторений в тексте, а так же ограничить результирующее количество ключевых слов.

Для написания данной статья я воспользовался статьей: Подсчет количества совпадений слов в массиве
Нужно взять функцию написанную в данной статье и модифицировать ее.

$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et " . "dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex" . " ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat" . " nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit" . " anim id est laborum.";

Будем считать, что текст содержащийся в переменной $text, это текст вашей статьи.
Создадим массив слов, упоминающийся в данном тексте.

Я разбираю текст на массив слов с условием, что слова разделены символом ‘пробел’.
Еще один пример разделения строки на массив слов.
Понимаю, что это не правильно, так как в массив могут попадать слова с лишними символами, но это только пример.

Так же можно применить альтернативный (и вероятно правильный)
вариант поиска слов в тексте с помощью регулярного выражения.

Ограничимся количеством возвращаемых ключевых слов:

$maxKeywordCount = 10; // Максимальное количество ключевых слов

Модифицированная функция подсчета слов в массиве:

/** * @param $arrayWords - Массив слов полученный из текста * @param int $repeatWordCount - Учитывать слова с указанным количеством повторений * @param int $minWordLength - Учитывать слова с данным количеством символов * * @return array - Полученный массив с ключевыми словами */ function keywords($arrayWords, $repeatWordCount = 2, $minWordLength = 3) { $tmpArr = []; $resultArray = []; foreach ($arrayWords as $val) { if (strlen($val) >= $minWordLength) { $val = mb_strtolower($val); if (array_key_exists($val, $tmpArr)) { $tmpArr[$val]++; > else { $tmpArr[$val] = 1; > > if ($tmpArr[$val] >= $repeatWordCount) {; $resultArray[$val] = $tmpArr[$val]; > >

$arrayWords — Массив слов
$repeatWordCount = 2 — Учитывать слова, которые повторяются указанное количество раз
$minWordLength = 3 — Учитывать слова длинна которых не менее указанного количества символов

В самой функции все слова приводятся к нижнему регистру, для корректного подсчета слов с буквами разного регистра.

Подсчитываем повторение слов и записываем с массив, где ключом является само слово, а значением количество повторений

if (array_key_exists($val, $tmpArr)) { $tmpArr[$val]++; > else { $tmpArr[$val] = 1; >

Далее в данном цикле мы пишем в результирующий массив слова с указанным минимальным количеством повторений:

if ($tmpArr[$val] >= $repeatWordCount) {; $resultArray[$val] = $tmpArr[$val]; >

Сортируем массив в обратном порядке, сохраняя ключи, для сортировки по убыванию слов с максимальным количеством повторений.

И напоследок отбираем требуемое, указанное количество слов:

array_slice(keywords($array), 0, $maxKeywordCount)

Функция array_slice нам нужна для отбора первых 10 значений массива (Указанных в переменной $maxKeywordCount).
Первым параметром в функцию array_slice мы передаем массив ключевых слов, вторым параметром указываем позицию с которой мы будем отбирать массив (в нашем случае это 0 позиция), третий параметр это конечная позиция элемента.

/** * @param $arrayWords - Массив слов полученный из текста * @param int $repeatWordCount - Учитывать слова с указанным количеством повторений * @param int $minWordLength - Учитывать слова с данным количеством символов * * @return array - Полученный массив с ключевыми словами */ function keywords($arrayWords, $repeatWordCount = 2, $minWordLength = 3) { $tmpArr = []; $resultArray = []; foreach ($arrayWords as $val) { if (strlen($val) >= $minWordLength) { $val = mb_strtolower($val); if (array_key_exists($val, $tmpArr)) { $tmpArr[$val]++; > else { $tmpArr[$val] = 1; > > if ($tmpArr[$val] >= $repeatWordCount) {; $resultArray[$val] = $tmpArr[$val]; > > arsort($resultArray); return $resultArray; > var_dump(array_slice(keywords($array, 1), 0, $maxKeywordCount));

Результат выполнения кода:

‘dolore’ => int 2
‘dolor’ => int 2
‘occaecat’ => int 1
‘reprehenderit’ => int 1
‘voluptate’ => int 1
‘velit’ => int 1
‘esse’ => int 1
‘cillum’ => int 1
‘fugiat’ => int 1
‘nulla’ => int 1

В результате мы получили 10 ключевых слов. 2 Из которых имеют 2 повторения в тексте, остальные по одному.
По хорошему на будущее нужно реализовать отбор слов через регулярное выражения с условием отбора на любой знак, кроме букв, включая пробел.
Возможно в будущем статья будет дописана и доработана.
На этом все.

Источник

Читайте также:  Python dictionary for iterate
Оцените статью