>  기사  >  백엔드 개발  >  줄 바꿈 - [PHP] PHP를 사용하여 순수 영어 텍스트의 단어 수를 계산할 때 이런 현상이 발생하는 이유는 무엇입니까?

줄 바꿈 - [PHP] PHP를 사용하여 순수 영어 텍스트의 단어 수를 계산할 때 이런 현상이 발생하는 이유는 무엇입니까?

WBOY
WBOY원래의
2016-12-01 00:56:351072검색

코드는 다음과 같습니다.

<code><?php
/**
* 任一个英文的纯文本文件,统计其中的单词出现的个数。
* Created by PhpStorm.
* User: Paul
* Date: 2016/11/5
* Time: 23:18
*/

$content = file_get_contents('4/Gone with the wind.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(';', '', $string);
    $string = str_replace(',', '', $string);
    $string = str_replace('.', '', $string);
    $string = str_replace('.', '', $string);
    $string = str_replace('‘', '', $string);
    $string = str_replace('?', '', $string);
    $string = str_replace('“', '', $string);
    $string = str_replace('”', '', $string);
    $string = str_replace('―', '', $string);
    $string = str_replace('-', '', $string);
    $string = str_replace('!', '', $string);
    $string = str_replace(':', '', $string);
    $string = str_replace('(', '', $string);
    $string = str_replace(')', '', $string);

    $array = explode(' ', trim($string));

    $res = array();
    foreach ($array as $key=>$value) {
        //过滤掉如I’ll、you’re、masters’s等单词
        if (strpos($value, '’') !== false || strpos($value, "'") !== false) {
            continue;
        }

        //过滤掉空
        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;
}</code>

출력 결과:

<code>array(
    [repression] => 1
    [thoroughness] => 1
    [bleached] => 1
    [tow] => 1
    [inspired] => 1
    [uniformwell] => 1
    [panamas] => 1
    [caps
when] => 1
)</code>

왜 두 단어가 하나의 단어로 판단되는지 이해가 되지 않습니다. txt는 숭고하게 열렸고 인코딩은 UTF-8로 설정되었습니다. 컴퓨터에 포함된 텍스트 문서 도구로 열거나 편집하지 않았습니다. 또한 구두점을 필터링하는 경우도 있었고 처리를 위해 rn 필터링도 추가했지만 아무런 효과가 없어 코드가 제거되었습니다. 이런 일이 발생하는 이유와 이를 방지하는 방법을 알아보세요.

답글 내용:

코드는 다음과 같습니다.

<code><?php
/**
* 任一个英文的纯文本文件,统计其中的单词出现的个数。
* Created by PhpStorm.
* User: Paul
* Date: 2016/11/5
* Time: 23:18
*/

$content = file_get_contents('4/Gone with the wind.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(';', '', $string);
    $string = str_replace(',', '', $string);
    $string = str_replace('.', '', $string);
    $string = str_replace('.', '', $string);
    $string = str_replace('‘', '', $string);
    $string = str_replace('?', '', $string);
    $string = str_replace('“', '', $string);
    $string = str_replace('”', '', $string);
    $string = str_replace('―', '', $string);
    $string = str_replace('-', '', $string);
    $string = str_replace('!', '', $string);
    $string = str_replace(':', '', $string);
    $string = str_replace('(', '', $string);
    $string = str_replace(')', '', $string);

    $array = explode(' ', trim($string));

    $res = array();
    foreach ($array as $key=>$value) {
        //过滤掉如I’ll、you’re、masters’s等单词
        if (strpos($value, '’') !== false || strpos($value, "'") !== false) {
            continue;
        }

        //过滤掉空
        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;
}</code>

출력 결과:

<code>array(
    [repression] => 1
    [thoroughness] => 1
    [bleached] => 1
    [tow] => 1
    [inspired] => 1
    [uniformwell] => 1
    [panamas] => 1
    [caps
when] => 1
)</code>

왜 두 단어가 하나의 단어로 판단되는지 이해가 되지 않습니다. txt는 숭고하게 열렸고 인코딩은 UTF-8로 설정되었습니다. 컴퓨터에 포함된 텍스트 문서 도구로 열거나 편집하지 않았습니다. 또한 구두점을 필터링하는 경우도 있었고 처리를 위해 rn 필터링도 추가했지만 아무런 효과가 없어 코드가 제거되었습니다. 이런 일이 발생하는 이유와 이를 방지하는 방법을 알아보세요.

문제는 줄바꿈(및 캐리지 리턴)이 처리되지 않고 해당 필터 문자가 ''로 대체된다는 것입니다. 이 문자는 ''으로 대체되어야 합니다.

<code class="php"><?php
$content = file_get_contents(__FILE__); //没有你的原始文本, 所以就直接读取文件自身作为样本了
$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 $key=>$value) {
        //过滤掉空
        if (!$value) {
            continue;
        }

        //过滤掉如I’ll、you’re、masters’s等单词
        if (strpos($value, '’') !== false || strpos($value, "'") !== false) {
            continue;
        }

        if (array_key_exists($value, $res)) {
            $res[$value]++;
        } else {
            $res[$value] = 1;
        }
    }

    //排序
    array_multisort($res, SORT_DESC, SORT_NUMERIC);
    return $res;
}</code>

파일의 문자열이 어떻게 생겼는지 모르겠지만 trim 기능은 양쪽 공백(rn)만 제거하므로 문제가 여기에 있는 것 같습니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.