基于单词列表的分类 Python
我想对文本进行分类:积极、消极或中立。我有一份积极和消极的单词列表。我想用Python来实现这个功能。下面是我想的代码大概样子:
如果文本中的单词在积极单词列表里,那么 积极计数器加1
如果文本中的单词在消极单词列表里,那么 消极计数器加1
总计数 = 积极计数 + 消极计数
如果总计数的长度大于0: 存入积极数据库 否则如果总计数的长度小于0: 存入消极数据库 否则:
store in neutral database
这就是我的大致想法,但我对编程一窍不通。 我在用mongodb存储数据,这部分我没有问题,但我还是无法进行分类。 有没有人能帮帮我?
1 个回答
1
除了字符串比较和控制流程语句,列表推导式在这里也会很有用。
text = "seeking help on possible homework task"
raw_words = text.split(" ")
positive_words = ['seeking','help']
negative_words = ['homework']
positive_score = len([word for word in raw_words if word in positive_words])
negative_score = len([word for word in raw_words if word in negative_words])
total_score = positive_score - negative_score
这样一来,total_score
的值就会变成1
。