【问题标题】:PHP count word frequency with support for punctuation marks支持标点符号的 PHP 计数词频
【发布时间】:2020-03-19 10:33:30
【问题描述】:

我正在尝试从正文中获取常用短语的计数。我不只是想要单个单词,而是任何停用词之间的所有单词系列。例如,https://en.wikipedia.org/wiki/Wuthering_Heights 我希望计算“呼啸山庄”这个短语,而不是“呼啸山庄”和“身高”。

if (in_array($word, $this->stopwords)) 
{
    $cleanPhrase = preg_replace("/[^A-Za-z ]/", '', $currentPhrase);
    $cleanPhrase = trim($cleanPhrase);
    if($cleanPhrase != "" && strlen($cleanPhrase) > 2)
    {
        $this->Phrases[$cleanPhrase] = substr_count($normalisedText, $cleanPhrase);
        $currentPhrase = "";
    }
    continue;
}
else

$currentPhrase = $currentPhrase . $word . " ";

如果使用“阶段”这个词,我对这个“年龄”的问题就会被计算在内。这里的解决方案是在$cleanPhrase 变量的任一侧添加空格。这导致的问题是如果没有空白。可能有逗号、句号或其他表示某种标点符号的字符。我想计算所有这些。有没有办法我可以做到这一点而不必做这样的事情。

$terminate = array(".", " ", ",", "!", "?");
$count = 0;
foreach($terminate as $tpun)
{
    $count += substr_count($normalisedText, $tpun . $cleanPhrase . $tpun);
}

【问题讨论】:

  • 哇哦 PHP 上的频率计数器。我有一个非常相似的项目。虽然我是用 C++ 编写的,但解决方案的想法可能是相同的。解析文本时 - 我使用空格、换行符、制表符作为分隔符,然后对于每个单词,我确定该单词是否有其他标点符号 - 逗号等,记住单词有,然后根据记住的标点符号形成短语.它实际上有点复杂,但主要思想是分别记住每个单词的标点符号。虽然是的,但它会导致很多 if ... else if ... 声明。

标签: php text analysis substr-count


【解决方案1】:

通过使用this answer 稍作修改,您可以这样做:

$sentence = "Age: In this day and age, people of all age are on the stage.";
$word = 'age';
preg_match_all('/\b'.$word.'\b/i', $sentence, $matches);

\b 表示单词边界。因此,如果搜索 age,则该字符串的计数为 3(模式中的 i 标志表示不区分大小写,如果您也想匹配大小写,也可以将其删除)。

如果您一次只匹配一个短语,您将在count($matches[0]) 中找到您的计数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 2013-06-14
    • 1970-01-01
    • 2012-06-13
    • 2011-08-07
    • 1970-01-01
    相关资源
    最近更新 更多