以此字符串为例:“将在明天在伦敦和明天在肯特见到你”。php - 如何将字符串转换为其关键字的关联数组
如何将它转换为包含该关键字作为关键字的关联数组,同时优选错过的常用词,像这样:
阵列([明天] => 2 [伦敦] => 1 [肯特] => 1)
任何帮助非常感谢。
以此字符串为例:“将在明天在伦敦和明天在肯特见到你”。php - 如何将字符串转换为其关键字的关联数组
如何将它转换为包含该关键字作为关键字的关联数组,同时优选错过的常用词,像这样:
阵列([明天] => 2 [伦敦] => 1 [肯特] => 1)
任何帮助非常感谢。
用字的黑名单不包含
$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);
我会说你可以:
explode
preg_split
array_filte
r只保留行(即话)你想
array_count_values
返回false
编辑:和,只是为了好玩,这里有一个简单的例子:
首先,字符串,这被分解成字:
$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)
然后,filteting:
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
现在,你来从这里;-)
主要建立,你必须去努力:
玩得开心!
你可以有常用词表,然后通过你的字符串去一个字的时间,检查它是否在该表存在,如果没有,那么它+1添加到您的关联数组,或者如果它已经存在。
快给我。再次舀。 – dnagirl 2010-04-29 18:45:53
'str_word_count'也可能很有趣:http://www.php.net/manual/en/function.str-word-count.php – 2010-04-29 18:55:12
谢谢你的作品。有没有可能获得最终结果“int”?即只是自己的号码 – Steven 2010-04-29 19:00:16