以这个字符串为例:“明天伦敦见,后天肯特见”。
我如何将其转换为包含关键字作为键的关联数组,同时最好遗漏常用词,如下所示:
数组 ( [明天] => 2 [伦敦] => 1 [肯特] => 1)
非常感谢任何帮助。
最佳答案
我会说你可以:
- 将字符串拆分为单词数组
- 与
explode
- 或
preg_split
- 取决于您接受的单词分隔符的复杂程度
- 与
- 使用
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/