今天在寫一個指令碼,統計一個純英文的文字文件txt,裡面的單詞出現的數量的時候呢,代碼如下:
<?php/*** 任一個英文的純文字檔案,統計其中的單詞出現的個數。* Created by PhpStorm.* User: Paul* Date: 2016/11/5* Time: 23:18*/$content = file_get_contents('4/youth.txt');$res = count_word($content, 1);print_r($res);/*** 任一個英文的純文字檔案,統計其中的單詞出現的個數。* @param string $string 字串* @param int $lower 是否大小寫 1:不區分大小寫 0:區分大小寫* @return array*/function count_word($string, $lower = 0) { $string = trim($string); if ($lower) { $string = strtolower($string); } //過濾掉一些標點符號 $string = str_replace([';', ',', '.', '‘', '?', '“', '”', '―', '-', '!', ':', '(', ')', '…', ' ', '"', '(', ')', '。', '\r', '\n'], ' ', $string); $array = explode(' ', $string); $res = array(); foreach ($array as $value) { //把如I’ll、you’re、masters’s等單詞後面引號的過濾掉,只留下I、you、master等單詞 if (strpos($value, '’') !== false) { $value = strstr($value, '’', true); } if (strpos($value, "'") !== false) { $value = strstr($value, "'", true); } //過濾掉空 if (empty($value) === true) { continue; } if (array_key_exists($value, $res)) { $res[$value]++; } else { $res[$value] = 1; } } //排序 array_multisort($res, SORT_DESC, SORT_NUMERIC); return $res;}
運行之後呢,遇到了一種情況,會把一個單詞後面換行之後接著一個單詞,這兩個單詞會被判斷成一個單詞,如下:
array( [repression] => 1 [thoroughness] => 1 [bleached] => 1 [tow] => 1 [inspired] => 1 [uniformwell] => 1 [panamas] => 1 [capswhen] => 1)
代碼中已經把\r、\n替換成空了,而且txt檔案不是用windows內建的文本工具開啟編輯的,是用sublime開啟的並且已經設定編碼為utf-8了,但還是會出現這種情況。
解決:通過在 segmenfault提問以及 尋找一些資料才得以解決,原因是, 引用逸出字元的時候呢,要用雙引號,不能用單引號,這個和引用變數的時候是同個道理的,比如:
<?php$aa = '你好\r\n我不好';echo $aa;$bb = "你好\r\n我不好";echo $bb;
輸出:
你好\r\n我不好你好我不好
所以,上面的代碼要修改為:
<?php/*** 任一個英文的純文字檔案,統計其中的單詞出現的個數。* Created by PhpStorm.* User: Paul* Date: 2016/11/5* Time: 23:18*/$content = file_get_contents('4/youth.txt');$res = count_word($content, 1);print_r($res);/*** 任一個英文的純文字檔案,統計其中的單詞出現的個數。* @param string $string 字串* @param int $lower 是否大小寫 1:不區分大小寫 0:區分大小寫* @return array*/function count_word($string, $lower = 0) { $string = trim($string); if ($lower) { $string = strtolower($string); } //過濾掉一些標點符號(注意:分行符號\r、\n等必須用雙引號,不能用單引號) $string = str_replace([';', ',', '.', '‘', '?', '“', '”', '―', '-', '!', ':', '(', ')', '…', ' ', '"', '(', ')', '。', "\r", "\n"], ' ', $string); $array = explode(' ', $string); $res = array(); foreach ($array as $value) { //把如I’ll、you’re、masters’s等單詞後面引號的過濾掉,只留下I、you、master等單詞 if (strpos($value, '’') !== false) { $value = strstr($value, '’', true); } if (strpos($value, "'") !== false) { $value = strstr($value, "'", true); } //過濾掉空 if (empty($value) === true) { continue; } if (array_key_exists($value, $res)) { $res[$value]++; } else { $res[$value] = 1; } } //排序 array_multisort($res, SORT_DESC, SORT_NUMERIC); return $res;}