gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 12:52:56 24 4
gpt4 key购买 nike

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

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

数组 ( [明天] => 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com