There are 9 texts called text1, text2, ... text9. A function is defined as follow.
def lexical_diversity(text):
return len(set(text))/len(text)
I want to call the function for all 9 texts with following code. But the outpu is wrong.
for i in range(1,10):
a='text'+str(i)
print(lexical_diversity(a))
My output is
0.8
0.8
...
0.8
If applying the function to text1, I get following result.
>>>lexical_diversity(text1)
Out[37]:0.07406285585022564
So which part goes wrong?
2 Answers 2
You should understand that a = 'text' + str(i) does not magically bestow upon a the value of whatever is contained inside the variable text1. Instead, a is assigned to the string "text1". The two are not the same.
Given the names, you should probably consider storing your texts in a list:
texts = [text1, text2, text3, ...]
And now,
for a in texts:
print(lexical_diversity(a))
7 Comments
texts[i] sounds better than texts["text"+str(i)].text1, text2, .... He merely have texts, and added a number to his variables names.texts = [globals()['text' + str(i)] for i in range(1, 10)] You must wonder... why not use globals directly? Well, it's major code smell.Python3
def lexical_diversity(text):
return len(set(text))/len(text)
lista = []
for i in range(1,10):
lista.append("text%d" % i)
for resVal in lista:
print(resVal)
print(lexical_diversity(resVal))
'text'+str(i)gives"text1","text2", ... the actual strings. So you get the lexical diversity of"text1","text2", ... If you have multiple texts you want to access, you probably want to store them in an array, not in separated variables otherwise you cannot loop on them.python list tutorialon your search engine of choice, you'll get a better understanding of how to handle lists of things :)