Search code examples
pythonfunctiontokennltkcounter

How to increase count if function called by another function in Python


I am trying to count all tokens given by func1 and print out the result from func2. The problem is that each time func2 gets called the counter does not update for natural reasons because we call the function over and over again. Are there any ways of solving this? NOTE: only func2 is supposed to be changed

import nltk

def func1(tokens):
    listOfTokens = tokens.split()
    for token in listOfTokens:
        func2(token)

def func2(token):
    count = 0
    nltk_tokens = nltk.word_tokenize(token)
    count += len(nltk_tokens)
    print(count) # expected to be 4 but is printing : 1 1 1 1

func1("A b c d")

Solution

  • You can do like this

    import nltk
    
    count = 0
    def func1(tokens):
        listOfTokens = tokens.split()
        for token in listOfTokens:
            func2(token)
    
    def func2(token):
        global count
        nltk_tokens = nltk.word_tokenize(token)
        count += len(nltk_tokens)
        print(count) # expected to be 4 but is printing : 1 1 1 1
    
    func1("A b c d")