PHP代码创建负面单词字典并搜索帖子是否有负面单词

时间:2017-03-15 03:45:31

标签: php search sentiment-analysis words

我正在尝试开发一个PHP应用程序,它接受用户的评论,然后匹配字符串以检查评论是肯定还是否定。我在negative.txt文件中有负面词的列表。如果一个单词与单词列表匹配,那么我想要一个简单的整数计数器增加1.我尝试了一些链接并创建了一个代码来检查注释是否为负数或正数但它只匹配最后一个单词该文件的代码。这就是我所做的代码。

    <?php 
    function teststringforbadwords($comment) 
    {
      $file="BadWords.txt";
      $fopen = fopen($file, "r");
      $fread = fread($fopen,filesize("$file"));
      fclose($fopen);
      $newline_ele = "\n";
      $data_split = explode($newline_ele, $fread);
      $new_tab = "\t";
      $outoutArr = array();
      //process uploaded file data and push in output array
      foreach ($data_split as $string)
      {
          $row = explode($new_tab, $string);
          if(isset($row['0']) && $row['0'] != ""){
              $outoutArr[] = trim($row['0']," ");
          }
      }
      //---------------------------------------------------------------
        foreach($outoutArr as $word) {

        if(stristr($comment,$word)){
            return false;
        }
    }
    return true;
}

    if(isset($_REQUEST["submit"]))
    {
        $comments = $_REQUEST["comments"];
        if (teststringforbadwords($comments)) 
        {
            echo 'string is clean';
        }
        else
        {
            echo 'string contains banned words';
        }
    }
    ?>

链接已尝试:Check a string for bad words?

2 个答案:

答案 0 :(得分:1)

我在strtolower和您输入的文件中添加了$comments函数。这样,如果有人拼写STUPID而不是stupid,代码仍会检测到坏词。

我还添加了trim来删除不必要的和破坏性的空格(如换行符)。

最后,我改变了检查单词的方式。我使用preg_match来分割所有空格,因此我们只检查完整的单词,并且不会意外地禁止不正确的字符串。

<?php 
    function teststringforbadwords($comment) 
    {
      $comment = strtolower($comment);
      $file="BadWords.txt";
      $fopen = fopen($file, "r");
      $fread = strtolower(fread($fopen,filesize("$file")));
      fclose($fopen);
      $newline_ele = "\n";
      $data_split = explode($newline_ele, $fread);
      $new_tab = "\t";
      $outoutArr = array();
      //process uploaded file data and push in output array
      foreach ($data_split as $bannedWord)
      {
          foreach (preg_split('/\s+/',$comment) as $commentWord) {
              if (trim($bannedWord) === trim($commentWord)) {
                  return false;
              }
          }
    }
    return true;
}

答案 1 :(得分:1)

1)您的存储$row['0']仅为什么不存储其他索引字。所以问题是你忽略了文本文件中的一些单词。

Some suggestion

1)将文本插入文本文件one by one,即这样的新行,这样您就可以轻松访问换行符以避免多次爆炸和循环。

 Example: sss.txt
 ...
 bad
 stupid
 ...
 ...

2)对注释和坏字符串应用修剪和小写功能。

希望它能按预期工作

function teststringforbadwords($comment) 
{
  $file="sss.txt";
  $fopen = fopen($file, "r");
  $fread = fread($fopen,filesize("$file"));
  fclose($fopen);

  foreach(explode("\n",$fread) as $word) 
  {

    if(stristr(strtolower(trim($comment)),strtolower(trim($word))))
    {
        return false;
    }
  }
  return true;
}