php - 如何将字符串转换为其关键字的关联数组

Ste*_*ven 7 php arrays

以此字符串为例:"明天将在伦敦见到你,明天将在肯特见到你".

我如何将其转换为包含关键字作为键的关联数组,同时最好错过常用词,如下所示:

数组([明天] => 2 [伦敦] => 1 [肯特] => 1)

任何帮助非常感谢.

Pas*_*TIN 7

我会说你可以:

  • 将字符串拆分为单词数组
    • explode
    • 要么 preg_split
    • 取决于您对单词分隔符所接受的复杂程度
  • 使用array_filter只保留你想要的线条(即单词)
    • 回调函数必须为所有非有效字返回false
  • 然后,array_count_values在结果列表中 使用
    • 这将计算单词数组中每个单词出现的次数



编辑:而且,只是为了好玩,这是一个简单的例子:

首先,字符串会爆炸成单词:

$str = "will see you in London tomorrow and Kent the day after tomorrow";
$words = preg_split('/\s+/', $str, -1, PREG_SPLIT_NO_EMPTY);
var_dump($words);
Run Code Online (Sandbox Code Playgroud)

哪个让你:

array
  0 => string 'will' (length=4)
  1 => string 'see' (length=3)
  2 => string 'you' (length=3)
  3 => string 'in' (length=2)
  4 => string 'London' (length=6)
  5 => string 'tomorrow' (length=8)
  6 => string 'and' (length=3)
  7 => string 'Kent' (length=4)
  8 => string 'the' (length=3)
  9 => string 'day' (length=3)
  10 => string 'after' (length=5)
  11 => string 'tomorrow' (length=8)
Run Code Online (Sandbox Code Playgroud)


然后,过滤:

function filter_words($word) {
    // a pretty simple filter ^^
    if (strlen($word) >= 5) {
        return true;
    } else {
        return false;
    }
}
$words_filtered = array_filter($words, 'filter_words');
var_dump($words_filtered);
Run Code Online (Sandbox Code Playgroud)

哪个输出:

array
  4 => string 'London' (length=6)
  5 => string 'tomorrow' (length=8)
  10 => string 'after' (length=5)
  11 => string 'tomorrow' (length=8)
Run Code Online (Sandbox Code Playgroud)


最后,计数:

$counts = array_count_values($words_filtered);
var_dump($counts);
Run Code Online (Sandbox Code Playgroud)

最后的结果是:

array
  'London' => int 1
  'tomorrow' => int 2
  'after' => int 1
Run Code Online (Sandbox Code Playgroud)


现在,由你来建立起来;-)
主要是,你必须努力:

  • 一个更好的爆炸函数,处理ponctuation (或在过滤期间处理)
  • "智能"过滤功能,比我的更好地满足您的需求

玩得开心 !


Gal*_*len 0

使用不包含的单词黑名单

$str = 'will see you in London tomorrow and Kent the day after tomorrow';
$skip_words = array( 'in', 'the', 'will', 'see', 'and', 'day', 'you', 'after' );
// get words in sentence that aren't to be skipped and count their values
$words = array_count_values( array_diff( explode( ' ', $str ), $skip_words ) );

print_r( $words );
Run Code Online (Sandbox Code Playgroud)