Replace the text with an accidental word from



  • I'm writing a bot telegram. There are boxes in the bolt, and I'd like to add a function like a light word on the mail. I mean, a man writes:

    How are you? It's Vanya. Okay.

    Can you tell me how to do that script take the early words in the brackets? Let's just say:

    Hi, it's Vanya. Good-bye.

    How's it going? Good-bye.

    I've tried to use the line format, but if the user leads more than one of those lines, it'll be a mistake.

    Here's the code:

    import random
    

    class RandomText(object):
    def format(self, format):
    return random.choice(format.split('|'))

    print('fef fe efe {:Привет|Пока}'.format(RandomText()))



  • What's wrong with the decision?

    import random
    

    text = f"{random.choice(['Привет', 'Как дела'])} Это Ваня. Ну ладно {random.choice(['Пока', 'Прощай'])}"
    print(text)

    or, in your case,

    text = f"{random.choice('Привет|Как дела'.split('|'))} Это Ваня. Ну ладно {random.choice('Пока|Прощай'.split('|'))}"

    And, of course, you can't do one line:

    text1 = random.choice('Привет|Как дела'.split('|'))
    text2 = random.choice('Пока|Прощай'.split('|'))
    text = f"{text1} Это Ваня. Ну ладно {text2}"

    P. S.

    You understand your case, you need regular expressions.

    The principle of work is as follows:

    1. looking for all types of structures {}

    2. Then, in a series of passes, received by accident and replaced

    This is the example of the code:

    import re
    import random

    text = "Проверка {Ваня|Петя|Таня} работы {1|2|3|4|5} вского"

    blocks = re.findall(r"{(.*?)}", text)

    res = text
    for block in blocks:
    value = random.choice(block.split('|'))
    res = re.sub(r"{(.*?)}", value, res, 1)

    print(res)


Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2