How to make a text generator according to the possibilities I put in it

Asked

Viewed 344 times

-2

I’ve been looking for a few days on how to match a text randomly according to the possibilities I place within the parentheses. Example: (Hello, Hi, Good afternoon) how are you (your day is great?, how long!!!) My question is: how do I generate a different text with one of the possibilities that has there inside the parentheses, what is outside is to remain the same. Somebody give me a luzzzzzzzzzzzzzzzz, I’m trying in python

  • The texts between parentheses already belong to the string or they can be in different structures, like a tuple?

  • if you use an array and put to pull a random value every time it would not work? Use the date of the day.. the time .. something like, put it into a math account.. Depending on the number that drops, a message will appear.

2 answers

4

Python has a native function for this: random.choice.

from random import choice

saudacoes = ('Olá', 'Oi', 'Boa tarde')
saudacao = choice(saudacoes)

print(f'{saudacao}, como vai você?')

This way, every time the code is executed, a string of saudacoes shall be chosen at random.

  • That’s right, thank you very much, I hadn’t learned that part yet, I was doing a bit of a rumble here and it wasn’t working out. Vlw himself

-1

Place the options inside a tuple, shuffle with the Random.shuffle method, and take the first position.

from random import shuffle

op1 = ['Olá', 'Oi', 'Boa tarde']
shuffle(op1)

op2 = ['o seu dia está ótimo?', 'a quanto tempo!!!']
shuffle(op2)

print "{} como vai você {}".format(op1[0], op2[0])

this way, the sentences will change, automatically

  • 3

    To clarify, I voted against because I didn’t see the advantages of using the library random, but do not use the function choice, that has been implemented to address this problem.

  • But it’s an option that works, and it would meet Wagner Rosa’s need, so I see no reason to vote against it. It only discourages those who want to help here. :-(

  • 2

    Don’t feel discouraged. You collaborated and received criticism. This will happen at all times, try to take advantage of them in a constructive way and you will grow together with the community. A solution, just because it works, doesn’t mean that can be used. The function suffle has not been implemented for this, so many who read the code will find it strange, which makes the code unclear; it affects performance, because shuffling all values whenever you need a new one is not a good idea.

  • I tested it here and both worked perfectly, Entering the function Choice was perfect for my purpose, thank you Rickadt and Anderson for learning.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.