如何解决使用词典查找文本中正面和负面单词的数量,
我想弄清楚如何创建一个列表列表,其中每个子列表都包含给定文本中肯定词和否定词的数量。下面是我正在使用的正面和负面文本文件的名称以及这些文本文件中的单词示例。也是“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 举报,一经查实,本站将立刻删除。