Created
February 7, 2012 18:28
-
-
Save aaronpk/1761119 to your computer and use it in GitHub Desktop.
Tries to find a good one-sentence summary from a wikipedia article.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| class WikiLayer { | |
| /* | |
| * wikilayer::getSignificantSentence() | |
| * ----------------------------------- | |
| * Grabs the first significant sentence from a wikipedia article | |
| */ | |
| public function getSignificantSentence($id) { | |
| $url = 'http://en.wikipedia.org/w/index.php?curid=' . $id; | |
| $html = $this->get_data($url); | |
| // Article text is between "bodytext" comment tags | |
| if(preg_match('/<!-- bodytext -->(.+)<!-- \/bodytext -->/s', $html, $match)) { | |
| $article = $match[1]; | |
| // Remove tables since they don't contain explanatory text | |
| $article = preg_replace('#<table[^>]*>.+?</table>#is', '', $article); | |
| // Remove thumbnail pictures | |
| $article = preg_replace('#<div class="thumb[^>]+>.+?</div>\s*</div>\s*</div>#s', '', $article); | |
| // Strip all remaining HTML tags to get plain text | |
| $article = strip_tags($article); | |
| // Split the text into sentences | |
| $sentences = preg_split('/(?<!(mr|ms|dr|mt|st))\.\s*/i', $article); | |
| // Look for the first sentence not in the format (* is * in *) | |
| $sentence = FALSE; | |
| foreach($sentences as $s) { | |
| $s = trim($s); | |
| if(preg_match('/.+ is .+ in .+/', $s) == FALSE) { | |
| $sentence = $s; | |
| break; | |
| } | |
| } | |
| return $sentence; | |
| } else { | |
| return false; | |
| } | |
| } | |
| protected function get_data($url) { | |
| $ch = curl_init(); | |
| curl_setopt($ch, CURLOPT_URL, $url); | |
| curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); | |
| curl_setopt($ch, CURLOPT_USERAGENT, 'Geoloqi (Geo-coded Wikipedia Article Layer) http://geoloqi.com'); | |
| $data = curl_exec($ch); | |
| return $data; | |
| } | |
| } | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment