Randomization of the python text



  • I'm trying to make the text random work. python♪ Using a tip from https://qna.habr.com/q/762919 I wrote this code:

    def get_random_choice(text):
        return random.choice(text)
    

    message = "{привет|здоров|здравствуйте|приветсвую} {вас|тебя}, как твои {дела|делишки}"
    matches = re.findall("{(.*?)}", message)

    all_mathces = []
    for match in matches:
    all_mathces.append(match.split('|'))

    res_text = ''
    for match in all_mathces:
    res_text += get_random_choice(match) + ' '

    print(res_text)

    Output: здравствуйте вас делишки

    Through the regular expression, I get all the meanings in the figure boxes and work with them, the question is, how do I combine the text with other words? Through a regular expression, get everything that's not in the figure brackets and then form a final line on the indexes of the two sets (recorded words and common)?

    And how realistic the data is to process the lines with the built {}, i.e. {|{|}}e.g.:

    message = "Hello {beautiful|{{very|slightly} |}{good|bad|neutral}} World{{?|!?}|!}"

    Whether I'm using the right approach, or if it's better to make a spontaneous reset of the line, like in https://www.cyberforum.ru/csharp-beginners/thread960396.html ?

    I would like to hear the views on the code and, in general, on this task. Maybe my code is too cumbersome, and it's much easier to do or there's a library like that on. pythonbecause I didn't find them. I'll be grateful for any help.



  • If there is no investment, the replacement itself can fit into one line.

    import random, re
    

    s = "{привет|здоров|здравствуйте|приветствую} {вас|тебя}, как твои {дела|делишки}"
    res = re.sub(r"{(.+?)}", lambda x: random.choice(x.group(1).split("|")), s)
    print(res)


    With the brackets placed in the cycle, the same rehexpom can be consistently set from the inner brackets to the outside.

    import random, re

    message = "Hello {beautiful|{{very|slightly} |}{good|bad|neutral}} World{{?|!?}|!}"
    while "{" in message:
    message = re.sub(r"{([^{}]+)}", lambda x: random.choice(x.group(1).split("|")), message)
    print(message)

    Or so. (to avoid infinity if the inlet is incorrect from the point of view of the bracketed row)

    import random, re

    message = "Hello {beautiful|{{very|slightly} |}{good|bad|neutral}} World{{?|!?}|!}"
    n = True
    while n:
    message, n = re.subn(r"{([^{}]+)}", lambda x: random.choice(x.group(1).split("|")), message)
    print(message)



Suggested Topics

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