2016-04-16 10 views
-3

Ich verstehe nicht, warum negative wird nicht erhöht, hält es das Zurücksetzen wieder auf 0.Python - Erhöhungsschritte in Schleife

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

Sorry über die Verzögerung.

UPDATE

Voll Code:

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 

OUTPUT

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}

Antwort

3

Sie müssen die negative Variable definieren, bevor sie in die Schleife Schritt:

negative = 0 
for line in neg_file: 
    # no changes 

Wie Sie vorgehen, wird jede einzelne Schleife "erstellt".

+0

habe ich schon das Top –

+2

@AdegokeA wirklich gemacht? Sie sollten das in Ihrem Code oben einschließen. –

+2

Wie würde es zurückgesetzt, wenn es nicht vor der Schleife definiert wurde? Soweit ich das beurteilen kann, sollte er einen Namensfehler werfen, wenn er ihn nicht vor der Schleife definiert. –

0

Ich habe positive und negative wieder auf Null vorzeitig zurückgesetzt. Sie sollten nach der for word in words: Schleife zurückgesetzt werden.