将列表添加到另一个列表?

时间:2017-02-09 19:42:33

标签: python

尝试使用单个标签列出所有单词。当我将不同的评论分成单词列表时,我会尝试将它们添加到名为pos / neg_bag_of_words的变量中。这似乎适用于一篇评论,但是当我遍历完整的评论语料库时,它似乎覆盖了一个标签的前一个单词列表,而其他标签列表的值为None。我究竟做错了什么?

#There are positive words in the entire corpus... but I get nothing
>>> pos_bag_of_words
    ['downloading',
 'illegally',
 'trailer',
 'looks',
 'like',
 'completely',
 'different',
 'film',
 'least',
 'have',
 'download',
 'haven',
 'wasted',
 'your',
 'time',
 'money',
 'waste',
 'your',
 'time',
 'this',
 'painful']

>>> neg_bag_of_words
[]

返回

    foreach($result as $key=>$value){
            if( "addonid" == $key && $value == $addonid ) {
                echo "The user have access to the addon!";
            }
    }

1 个答案:

答案 0 :(得分:3)

您应该将neg_bag_of_wordspos_bag_of_words的初始化置于for循环之外。否则,每次执行for循环时,您的列表都会重新初始化为空列表。这就是neg_bag_of_words没有得到任何结果的原因。做这样的事情:

pos_bag_of_words = []
neg_bag_of_words = []

for review, label in zip(reviews, labels):
    if label == 'NEGATIVE': 
        neg_bag_of_words = list(review.split()) + neg_bag_of_words
    if label == 'POSITIVE':
        pos_bag_of_words = list(review.split()) + pos_bag_of_words