0

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?

4
  • 1
    What does text1 contain? Commented Aug 24, 2017 at 11:45
  • 1
    '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. Commented Aug 24, 2017 at 11:45
  • @spectras I see my errors. Thanks. Anyway to fix it? Commented Aug 24, 2017 at 11:57
  • @LeiHao> well, I didn't add anything because cᴏʟᴅsᴘᴇᴇᴅ's answer below is the right way to do this. I would suggest you look for python list tutorial on your search engine of choice, you'll get a better understanding of how to handle lists of things :) Commented Aug 24, 2017 at 12:09

2 Answers 2

4

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))
Sign up to request clarification or add additional context in comments.

7 Comments

Given the names I would advocate an array. texts[i] sounds better than texts["text"+str(i)].
What I mean is given his variable names, I believe there is no semantic content in his text1, text2, .... He merely have texts, and added a number to his variables names.
I see my errors. Is there a way to create this list quickly, instead of typing text1, text2,...? A for-loop or something?
@LeiHao Yes. There's a quick and dirty solution. It involves manipulating globals. Do this: 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.
@akp That just puts strings in there, not the actual variable content.
|
0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.