Hello guys, I have been working over the following script to check if a particular word is a noun or not. For this , I open a file with lot of words in it and for each of the word, a check is made using if , if the the word in dictionary is similar to the word in argument . I think, for the purpose , this script is alright. But it is still returning false true everytime. Can you help me out with the issue? Following is the link to the dict.txt http://www.instantfilehosting.com/images/access/number-5021.txt <?php error_reporting(8191); if(checkNoun('test')) { echo 'noun'; } else { echo 'not a noun'; } print_r(error_get_last()); function checkNoun($a) { // check if the $a is noun $u=array(); // variable for testing $d=file('dict.txt'); // load the dictionary foreach($d as $k => $j) { // for each word in the dictionary ... if($j==$a) { // if the word is the one which is argumented , then... array_push($u,'y'); // ... push it in array } else { // if it is not the word ... // then do this... } } if($u['0']=='y') { // if even the first key of array is filled , then return false return false; } else { // or return true return true; } } ?> PHP:
The function replies true everytime , sorry for that , it was a silly mistake! And I am unable to edit the actual post!
How about the following function. if(checkNoun('test')) { echo 'noun'; } else { echo 'not a noun'; } function checkNoun($str){ $file = file('dict.txt'); foreach($file as $line){ $words = str_word_count($line, 1); if(array_search($str, $words)){ return true; } } return false; } PHP:
Thanks for your reply , but , won't this code return true for each dictionary word checked ? And yes I think , it is something related to \n in the $line variable that is preventing the script from functioning ... isn't it? The light flashed into my mind after using str_replace("\n","",$line); !!
Add trim out the \n \r function checkNoun($str){ $file = file('dict.txt'); foreach($file as $line){ $words = str_word_count($line, 1); $escape_words = array_map("trim", $words); //<--- we trim out the \n \r if(array_search($str, $escape_words)){ return true; } } return false; } PHP:
That should work. Another alternative could be you read the file line by line and than compare words using strcmp