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")
CodePudding user response:
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")
CodePudding user response:
Try to pass all tokens to func2 and make the counting.
def func1(tokens):
listOfTokens = tokens.split()
func2(listOfTokens)
def func2(listOfTokens):
count = 0
for token in listOfTokens:
nltk_tokens = nltk.word_tokenize(token)
count = len(nltk_tokens)
print(count) # expected to be 4 but is printing : 1 1 1 1