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

标签 php arrays

以这个字符串为例:“明天伦敦见,后天肯特见”。

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

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

非常感谢任何帮助。

最佳答案

我会说你可以:

  • 将字符串拆分为单词数组
  • 使用array_filte r 只保留你想要的行(即单词)
    • 回调函数必须为所有无效词返回 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);

哪个让你:

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)


然后,过滤:

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);

哪些输出:

array
  4 => string 'London' (length=6)
  5 => string 'tomorrow' (length=8)
  10 => string 'after' (length=5)
  11 => string 'tomorrow' (length=8)


最后,计数:

$counts = array_count_values($words_filtered);
var_dump($counts);

最终结果:

array
  'London' => int 1
  'tomorrow' => int 2
  'after' => int 1


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

  • 更好的爆炸函数,处理标点符号(或在过滤期间处理)
  • “智能”过滤功能,比我更适合你的需求

玩得开心!

关于php - 如何将字符串转换为其关键字的关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2739873/

相关文章:

python - 从不均匀的 numpy 数组中获取转置和/或从不均匀的 numpy 数组中获取平均值

java - 数组的唯一计算值

arrays - Matlab 对象数组的逻辑索引

php - 通过ajax从mySql获取变量到jQuery

php - 以编程方式自动填写和提交表单

php - WAMP 和 XAMPP 显示 PHP 而不是运行它

PHP 更新未使用复选框更新数据库

java - 不明白为什么我在填充这个二维数组时遇到索引越界异常

php - 警告 : mysql_error(): supplied argument is not a valid MySQL-Link resource

C++: ' arr ' 和 ' arr[] ' 有什么区别