10

PHP を使用して、テキストを 1 つの単語に分割したいと考えています。これを達成する方法はありますか?

私のアプローチ:

function tokenizer($text) {
    $text = trim(strtolower($text));
    $punctuation = '/[^a-z0-9äöüß-]/';
    $result = preg_split($punctuation, $text, -1, PREG_SPLIT_NO_EMPTY);
    for ($i = 0; $i < count($result); $i++) {
        $result[$i] = trim($result[$i]);
    }
    return $result; // contains the single words
}
$text = 'This is an example text, it contains commas and full-stops. Exclamation marks, too! Question marks? All punctuation marks you know.';
print_r(tokenizer($text));

これは良いアプローチですか?改善のアイデアはありますか?

前もって感謝します!

4

6 に答える 6

30

任意の Unicode 句読点文字に一致するクラス \p{P} を \s 空白クラスと組み合わせて使用​​します。

$result = preg_split('/((^\p{P}+)|(\p{P}*\s+\p{P}*)|(\p{P}+$))/', $text, -1, PREG_SPLIT_NO_EMPTY);

これは、1 つ以上の空白文字のグループに分割されますが、周囲の句読点も吸い込まれます。また、文字列の先頭または末尾の句読点にも一致します。これは、「しないでください」や「彼は「痛い」と言った」などのケースを区別します。

于 2009-04-26T10:24:50.277 に答える
13

トークン化 - strtok

<?php
$text = 'This is an example text, it contains commas and full stops. Exclamation marks, too! Question marks? All punctuation marks you know.';
$delim = ' \n\t,.!?:;';

$tok = strtok($text, $delim);

while ($tok !== false) {
    echo "Word=$tok<br />";
    $tok = strtok($delim);
}
?>
于 2009-04-26T10:23:26.973 に答える
3

文字列を分割する前に、まず文字列を小文字にします。これにより、i修飾子とその後の配列処理が不要になります。さらに、\W単語以外の文字の短縮形を使用し、+乗数を追加します。

$text = 'This is an example text, it contains commas and full stops. Exclamation marks, too! Question marks? All punctuation marks you know.';
$result = preg_split('/\W+/', strtolower($text), -1, PREG_SPLIT_NO_EMPTY);

編集Marcog が提案する代わりにUnicode 文字プロパティ   を使用します。(句読点と区切り文字) のようなものは、より具体的な文字をカバーします。\W [\p{P}\p{Z}]\W

于 2009-04-26T10:35:09.240 に答える
1

また、explodeメソッドを使用することもできます: http://php.net/manual/en/function.explode.php

$words = explode(" ", $sentence);
于 2012-10-10T00:23:46.320 に答える
1

行う:

str_word_count($text, 1);

または、ユニコードのサポートが必要な場合:

function str_word_count_Helper($string, $format = 0, $search = null)
{
    $result = array();
    $matches = array();

    if (preg_match_all('~[\p{L}\p{Mn}\p{Pd}\'\x{2019}' . preg_quote($search, '~') . ']+~u', $string, $matches) > 0)
    {
        $result = $matches[0];
    }

    if ($format == 0)
    {
        return count($result);
    }

    return $result;
}
于 2009-04-26T10:24:48.950 に答える
1

PHP strtok() 関数を使用して、大きな文字列から文字列トークンを取得することもできます。次のように使用できます。

 $result = array();
 // your original string
 $text = 'This is an example text, it contains commas and full stops. Exclamation marks, too! Question marks? All punctuation marks you know.';
 // you pass strtok() your string, and a delimiter to specify how tokens are separated. words are seperated by a space.
 $word = strtok($text,' ');
 while ( $word !== false ) {
     $result[] = $word;
     $word = strtok(' ');
 }

strtok()の PHPドキュメントの詳細を参照してください。

于 2009-04-26T10:29:45.413 に答える