【问题标题】:Iterating through list of lists and count matches with different list遍历列表列表并计算与不同列表的匹配
【发布时间】:2019-12-08 13:25:16
【问题描述】:

我是 python 新手,目前正在为我的硕士论文进行情绪分析。但是,我目前正在处理这个问题,我真的不知道如何解决它。

我需要在包含单词 BLA 的字符串中找到一个句子,然后将句子中的每个单词与我的正负单词词典进行比较。如果否定词多于肯定词,则计数器应该 +1。最后,我会得到类似:在文件 1 中,有 4 个否定句包含 BLA 一词。

到目前为止,我使用正则表达式删除了所有不包含单词 BLA 的句子。然后我将句子中的单词分开,并创建了一个列表列表。它看起来例如像这样:

[['we', 'underperform', 'because', 'of', 'BLA'], ['BLA', 'is', 'bad'], ['BLA', 'is', '好']]

现在我想将每个单词与否定词和肯定词的字典进行比较。由于我需要确定包含 BLA 一词的句子是肯定的还是否定的,所以在移动到第二个之前,我只在列表中的一个列表中计算它是很重要的。

这个特定示例的结果应该是 2,因为 2 个句子是否定的,一个是肯定的。

在我只寻找的其他情况下,例如文本中的否定词,我是这样做的:

# Reset the number of negative words to zero
negative_count=0

# For each negative word, count the number of occurrences
for j in range(len(negative_words)):

    negative_count=negative_count+text_devided.count(negative_words[j])

所以我可能会这样做,但在遍历列表的循环中。

如果您知道如何以不同的方式解决这个问题,我也愿意接受。

【问题讨论】:

    标签: python list loops frequency sentiment-analysis


    【解决方案1】:

    我猜你的意思是你的字典。

    ...每个单词都有否定词和肯定词的字典。

    python 列表。
    所以我会这样做:

    list_with_sentences = [['we', 'underperform', 'because', 'of', 'BLA'], ['BLA', 'is', 'bad'], ['BLA', 'is', 'good']]
    pos_words = 0
    neg_words = 0
    total_neg_count = 0
    for sentence in list_with_sentences:  
        for word in sentence:  
            for item in dictonary_pos_word:
                if item == word:
                   pos_words = pos_words + 1
    
            for item in dictonary_neg_word:
                if item == word:
                   neg_words = neg_words + 1
    
            if neg_words > pos_words:
               total_neg_count = total_neg_count + 1
    

    【讨论】:

      【解决方案2】:
      ls = [
           ['we', 'underperform', 'because', 'of', 'BLA'],
           ['BLA', 'is', 'bad'],
           ['BLA', 'is', 'good']
           ]
      
      positive_words = ("good",)
      negative_words = ("underperform", "bad")
      
      for line in ls:    
           score = sum(map(lambda w: 1 if w in positive_words else -1 if w in negative_words else 0, line))
      
           """
           Score < 0: Negative
           Score > 0: Positive
           Score = 0: Neutral or same number of positive/negative words
           """
      
           print("Sentence:", " ".join(line))
           print(" Score:", score)
      
           print()
      

      根据句子中有多少否定词、肯定词和“中性”词生成分数。

      输出:

      Sentence: we underperform because of BLA
       Score: -1
      
      Sentence: BLA is bad
       Score: -1
      
      Sentence: BLA is good
       Score: 1
      

      【讨论】:

        猜你喜欢
        • 2021-06-14
        • 1970-01-01
        • 1970-01-01
        • 2019-12-19
        • 2010-12-18
        • 2020-06-25
        • 2017-03-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多