首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >数学/统计问题分析字符串中的单词

数学/统计问题分析字符串中的单词
EN

Stack Overflow用户
提问于 2020-11-24 03:47:28
回答 2查看 30关注 0票数 0

需要一些帮助-我正在试着分析新闻文章。我有一个正面单词和负面单词的列表。我正在搜索文章内容,寻找单词a向上计数的实例。

我的问题是,负面单词列表比正面的要长得多,所以所有的结果都偏向于负面。

我正在寻找一种方法来使结果正常化,以便将正面单词与负面单词略微加权,以平衡找到负面单词的可能性相当高的事实。不幸的是,我不知道从哪里开始。

感谢您抽出时间阅读这篇文章。

下面是我到目前为止拥有的代码。

代码语言:javascript
复制
  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];
    
  }
EN

回答 2

Stack Overflow用户

发布于 2020-11-24 07:00:31

所以我不知道php,但这看起来不像是php的问题,而更多的是一个方法的问题。现在,当您分析一篇文章时,您会根据词典中的单词是否存在而将它们分配为正面或负面,但因为您的词典大小不同,您会觉得这没有给您提供对文章的公平分析。

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

票数 0
EN

Stack Overflow用户

发布于 2020-11-24 07:06:59

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

代码语言:javascript
复制
<?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的工作示例

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64975339

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档