Python - 循环增量

时间:2016-04-16 17:39:34

标签: python for-loop

我无法确定为什么negative不会增加,它会一直重置为0.

for line in neg_file:
    line = re.sub('[^a-zA-Z0-9-]', '', line)
    if line == word:
        negative += 1
        print "N: " + str(negative)

对延迟感到抱歉。

更新

完整代码:

tweets = json.loads(open('tweets.json').read())
pos_file = open("words/positive.txt", "r+")
neg_file = open("words/negative.txt", "r+")

list = []
dict = {}

positive = 1 #this part works fine
positive += 2
print positive
dict['positive'] = positive
print dict

negative = 0
positive = 0

for x in range(len(tweets)):
    text = tweets[x]['text']
    text = ' '.join(word for word in text.split() if len(word)>3)
    text = re.sub('[^a-zA-Z0-9 ]', '', text)
    words = text.split(" ")
    dict['word_count'] = len(words)
    #exact match
    #print words
    for word in words:
        pos_file = open("words/positive.txt", "r+")
        for line in pos_file:
            line = re.sub('[^a-zA-Z0-9-]', '', line)
            if line == word:
                positive += 1 #str(word) - wasnt working for string concat, so i switched to numbers
                print positive
        pos_file.close()
        dict['positive']  = positive 
        positive = 0
        negative = 0
        neg_file = open("words/negative.txt", "r+")

        for line in neg_file:
            line = re.sub('[^a-zA-Z0-9-]', '', line)
            if line == word:
                negative += 1
                print "N: " + str(negative)

        neg_file.close()
        dict['negative']  = negative
        negative = 0

    print dict
    list.append(dict)
    dict.clear()
print list

输出

3 {'positive': 3} {'positive': 0, 'negative': 0, 'word_count': 9} 1 {'positive': 0, 'negative': 0, 'word_count': 13} 1 inevitable N: 1 loss N: 1 {'positive': 0, 'negative': 0, 'word_count': 15} 1 {'positive': 0, 'negative': 0, 'word_count': 11} stumbles N: 1 {'positive': 0, 'negative': 0, 'word_count': 12}

2 个答案:

答案 0 :(得分:3)

在进入循环之前,您需要定义negative变量:

negative = 0
for line in neg_file:
    # no changes

您正在进行的方式,每个循环都会“创建”。

答案 1 :(得分:0)

我在预先成熟时将positivenegative重新设置为零。它们应在for word in words:循环后重置。