【问题标题】:Math / statistics problem analyse words in string数学/统计问题分析字符串中的单词
【发布时间】:2021-03-06 13:50:37
【问题描述】:

需要一些帮助 - 我正在尝试分析新闻文章。 我有一个积极词和消极词的列表。我正在文章内容中搜索单词 a 的实例。

我的问题是否定词列表比肯定词列表长很多,所以所有结果都偏向否定。

我正在寻找一种方法来规范化结果,以便积极词相对于消极词略微加权,以平衡找到消极词的机会相当高的事实。不幸的是,我不知道从哪里开始。

感谢您抽出宝贵时间阅读本文。

下面是我目前的代码。


  function process_scores($content)
  {
    $positive_score = 0;
    
    for ($i = 0; $i < count($this->positive_words); $i++) {
      if($this->positive_words[$i] != "")
      {
        $c = substr_count( strtolower($content) , $this->positive_words[$i] );
        if($c > 0)
        {
          $positive_score += $c;
        }  
      }
      
    }
    
    $negative_score = 0;
    
    for ($i = 0; $i < count($this->negative_words); $i++) {
      if($this->negative_words[$i] != "")
      {
        $c = substr_count( strtolower($content) , $this->negative_words[$i] );
        if($c > 0)
        {
          $negative_score += $c;
        }
      }
    }
      
    return ["positive_score" => $positive_score, "negative_score" => $negative_score];
    
  }

【问题讨论】:

标签: php math statistics


【解决方案1】:

我建议在输出中加入一个权重因子。确切的权重是通过反复试验确定的。我继续重构你的代码,因为有一些重复

<?php

class WordScore {
    private $negative_words = [];
    private $positive_words = [];
    
    private $positive_weight = 1;
    private $negative_weight = 1;
    
    public function setScore(float $pos = 1, float $neg = 1) {
        $this->negative_weight = $neg;
        $this->positive_weight = $pos;
    }
    
    public function processScores($content) {
        $positive_score = $this->countWords($content, $this->positive_words);
        $negative_score = $this->countWords($content, $this->negative_words);
        
        return [
            "positive_score" => $positive_score * $this->positive_weight, 
            "negative_score" => $negative_score * $this->negative_weight
            ]; 
    }
    
    private function countWords( string $content, array $words, float $weight = 1 ) {
        $count = 0;
        foreach( $words as $word ) {
            $count += substr_count( strtolower($content) , strtolower($word) );
        }
        return $count;
    }
    
} 
 

http://sandbox.onlinephpfunctions.com/code/19b4ac3c12d35cf253e9fa6049e91508e4797a2e 的工作示例

【讨论】:

    【解决方案2】:

    所以我不知道php,但这似乎不像是一个php问题,而更像是一个方法问题。现在,当您分析一篇文章时,您会根据单词是否在您的字典中来将它们分配为正面或负面,但由于您的字典大小不同,您会觉得这并不能让您对文章进行公平的分析.

    您可以尝试的一种方法是为文章中的每个单词分配一个值。如果您的字典中不存在某个单词,请让程序提示您通过命令行手动解释该单词。然后决定这个词是正面的、负面的还是中性的,并让程序将该词添加到适当的字典中。一开始这会很烦人,但是说英语的人几乎在我们所有的对话中都使用大致相同的 2000 个单词,因此在几篇文章之后,您将拥有强大的词典,而不必担心歪斜,因为每个单词都会被分配一个值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      • 2020-04-28
      相关资源
      最近更新 更多