首页 > 解决方案 > 我怎么能这样写for语句:因为我不在x中

问题描述

对于词分类,我定义了正面和负面词汇,我想识别中性词(有无穷多个中性词)

所以我这样做了:

def word_feats(word): 
return {word: True}   
voc_pos = [ 'beauty', 'good', 'happy']    
voc_neg = [ 'bad', 'sick','lazy']    
voc = voc_pos + voc_neg    
pos_feats = [(word_feats(pos), 'pos') for pos in voc_pos]     
neg_feats = [(word_feats(neg), 'neg')for neg in voc_neg]    
neu_feats = [(word_feats(neu), 'neu')for neu not in voc]

错误是:

"invalid syntax" for neu_feats = [(word_feats(neu), 'neu')for neu not in voc]

标签: pythonnltk

解决方案


继续@blue_note 的回答:

使用zip_longest()

def word_feats(word):
        return {word: True}

voc_pos = [ 'beauty', 'good', 'happy']
voc_neg = [ 'bad', 'sick','lazy']
voc = voc_pos + voc_neg

mylist = ['book']

pos_feats = [(word_feats(pos), 'pos') for pos in voc_pos]
neu_feats = [(word_feats(neu), 'neu') for neu in mylist if neu not in voc]
neg_feats = [(word_feats(neg), 'neg') for neg in voc_neg]

print([*zip_longest(pos_feats, neu_feats, neg_feats)])

输出

[(({'beauty': True}, 'pos'), ({'book': True}, 'neu'), ({'bad': True}, 'neg')), (({'good': True}, 'pos'), None, ({'sick': True}, 'neg')), (({'happy': True}, 'pos'), None, ({'lazy': True}, 'neg'))]

推荐阅读