如何检索我发推文最多的单词?

ben*_*ham 7 php twitter

我一直在阅读twitter的开发者网站,但是在RESP API中没有一种方法可以做到这一点,我认为这是Streaming Api,有人可以指导我如何做到这一点吗?我想要类似于tweetstats的东西,只是告诉我最多的推文.

谢谢回答

Kei*_*rey 10

这使用REST API,而不是Streaming API,但我认为它可以满足您的需求.唯一的限制是它受REST API限制为最新的200条推文,所以如果你在上周有200多条推文,那么它只会跟踪你最近200条推文中的单词.

请务必使用所需的用户名替换API调用中的用户名.

<?php

//Get latest tweets from twitter in XML format. 200 is the maximum amount of tweets allowed by this function.
$tweets = simplexml_load_file('https://api.twitter.com/1/statuses/user_timeline.xml?include_entities=true&include_rts=true&screen_name=kimkardashian&count=2');

//Initiate our $words array
$words = array();

//For each tweet, check if it was created within the last week, if so separate the text into an array of words and merge that array with the $words array
foreach ($tweets as $tweet) {
    if(strtotime($tweet->created_at) > strtotime('-1 week')) {
        $words = array_merge($words, explode(' ', $tweet->text));
    }
}

//Count values for each word
$word_counts = array_count_values($words);

//Sort array by values descending
arsort($word_counts);

foreach ($word_counts as $word => $count) {
    //Do whatever you'd like with the words and counts here
}

?>
Run Code Online (Sandbox Code Playgroud)

  • 如果你正在寻找更好的,恕我直言,你需要定义"更好" (2认同)