L
L
leham12020-05-07 16:17:28
Python
leham1, 2020-05-07 16:17:28

Can you help with "cb = lambda m: random.choice(m.group(1).split('|'))"?

Hello.
I found a code on the Internet that generates a unique text.

def rand_text(s):
    import re, random
    
    rgx = re.compile('\{([^{}]*)\}')
    cb = lambda m: random.choice(m.group(1).split('|'))
    
    while 1:
        r = rgx.sub(cb, s)
        
        if len(r) == len(s):
            return r
        
        s = r
 
if __name__ == '__main__':
    print(rand_text(u'{Привет|Ку}, %username%. Как {дел{а|ишки}|сам|жизнь|поживает твоя мамаша}?'))


It works great. But I want to improve it a little to fit my needs.
The problem is that I can't figure out how it works.
cb = lambda m: random.choice(m.group(1).split('|'))


The "m" argument is not passed anywhere.

Please help someone who can understand this

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Pankov, 2020-05-07
@leham1

Passed here:
rgx.sub(cb, s)
All regexp matches will be passed as an argument to this function.

cb = lambda m: \     # Это лямбда-функция с одним аргументом по имени m
    random.choice(   # результат функции вычисляется методом случайного выбора из
        m.group(1)   # текста (сопоставленного с первой скобкой регекспа)
        .split('|')  #  разбитого по символу "|"
    )

The regexp matches rgx = re.compile('\{([^{}]*)\}')chunks of text within curly braces, and m.group(1) will match that chunk each time the lambda is called.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question