使用词典查找文本中正面和负面单词的数量,

问题描述

我想弄清楚如何创建一个列表列表,其中每个子列表都包含给定文本中肯定词和否定词的数量。下面是我正在使用的正面和负面文本文件名称以及这些文本文件中的单词示例。也是“X_train”变量中的示例文本。以及输出应该是什么样子。


positive_words.txt # 快乐、很棒、很棒

negative_words.txt = # 悲伤、糟糕、可怜

X_train = ['食物很棒,服务很棒'、'我对我的食物很满意'、'我的食物味道不好'、'我很穷,所以买不起食物我很难过,但至少我有鸡肉']

X_train_lexicon_features = ?


上述变量的输出应该是什么样子。

print(X_train_lexicon_features)

输出: [[2,0],[1,[0,1],2]]

# 从上面给出的例子来看,X_train 变量中的第一个文本应该产生 [2,0],因为它有 'great' 和 'amazing' 这两个都在 positive_lexicon 中。 [正面,负面]


下面是一个计算正负词个数的类。

class LexiconClassifier():
    def __init__(self):
        self.positive_words = set()
        with open('positive-words.txt',encoding = 'utf-8') as iFile:
            for row in iFile:
                self.positive_words.add(row.strip())

        self.negative_words = set()
        with open('negative-words.txt',encoding='iso-8859-1') as iFile:
            for row in iFile:
                self.negative_words.add(row.strip())
    
    def count_pos_words(self,sentence):
        num_pos_words = 0
        for word in sentence.lower().split():
            if word in self.positive_words:
                num_pos_words += 1
        return num_pos_words

    def count_neg_words(self,sentence):
        num_neg_words = 0
        for word in sentence.lower().split():
            if word in self.negative_words:
                num_neg_words += 1
        return num_neg_words

这是我运行的代码,用于返回每个文本的正面词数。

myLC = LexiconClassifier()

X_train_lexicon_features = []

for i in X_train:
     X_train_lexicon_features.append(myLC.count_pos_words(i))

输出: [2,1,0]

我不确定如何将 'count_neg_words' 函数混合到上面的代码中,该代码也将返回如下列表:[[2,[ 0,2]]

感谢任何建议,并提前感谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)