Created
August 17, 2014 23:39
-
-
Save flangofas/b82dfa4ebe836a644c65 to your computer and use it in GitHub Desktop.
Count words from text file
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 | |
/* | |
* Count number of words from the given txt file | |
* @author Antonis Flangofas | |
* @date 18/08/2014 | |
*/ | |
class WordCounter | |
{ | |
const ASC = 2; | |
const DESC = 4; | |
private $word_count; | |
function __construct($file, $flag = '') | |
{ | |
if (!is_readable($file)) { | |
throw InvalidArgumentException('File does not exist!'); | |
} | |
//get text and add all words to an array then count the values | |
$this->word_count = array_count_values(str_word_count(strtolower(file_get_contents($file)), 1)); | |
return $this->word_count; | |
} | |
/* | |
* Sort array if needed either ASC or DESC using bitwise operators | |
*/ | |
final public function sortByOccurrence($flag) { | |
if ($flag & static::ASC) { | |
asort($this->word_count); | |
} | |
if ($flag & static::DESC) { | |
arsort($this->word_count); | |
} | |
return $this->word_count; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment