我正在为我的论坛设置一个推特风格的"趋势主题"框.我有最受欢迎/单词/,但甚至不能开始考虑如何获得流行的短语,如Twitter.
就目前而言,我只是将最后200个帖子的所有内容都分成一个字符串并将它们分成单词,然后根据哪些单词的使用次数排序.如何将这一点从最流行的单词转换为最流行的短语?
您可能会考虑的一种技术是在 Redis 中使用 ZSET 来实现类似的目的。如果您有非常大的数据集,您会发现可以执行以下操作:
$words = explode(" ", $input); // Pseudo-code for breaking a block of data into individual words.
$word_count = count($words);
$r = new Redis(); // Owlient's PHPRedis PECL extension
$r->connect("127.0.0.1", 6379);
function process_phrase($phrase) {
global $r;
$phrase = implode(" ", $phrase);
$r->zIncrBy("trending_phrases", 1, $phrase);
}
for($i=0;$i<$word_count;$i++)
for($j=1;$j<$word_count - $i;$j++)
process_phrase(array_slice($words, $i, $j));
Run Code Online (Sandbox Code Playgroud)
要检索最热门的短语,您可以使用以下命令:
// Assume $r is instantiated like it is above
$trending_phrases = $r->zReverseRange("trending_phrases", 0, 10);
Run Code Online (Sandbox Code Playgroud)
$trending_phrases将是一系列十大热门短语。要执行诸如最近趋势短语(而不是一组持久的全局短语)之类的操作,请复制上面的所有 Redis 交互。对于每次交互,使用一个表示今天时间戳和明天时间戳(即:自 1970 年 1 月 1 日以来的天数)的密钥。当使用 检索结果时$trending_phrases,只需检索今天和明天(或昨天)的密钥并使用array_merge和array_unique来查找并集。
希望这可以帮助!