Функция sub в regex может принимать функцию в качестве аргумента repl.
📄 Из документации:
If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.
То есть для каждого совпадения будет вызвана функция для вычисления замены вместо замены на одну и ту же строку для всех совпадений.
Иными словами, для замены разных совпадений на разные строки не потребуется запускать re.sub() много раз для каждой строки замены. Достаточно определить функцию, которая вернёт строку для каждого из совпадений.
Описание слишком запутанное🤔, давайте лучше рассмотрим на простом примере:
Создаем карту замены. То есть какие строки на какие требуется менять.
remap = {
'раз': '1',
'два': '2',
'три': '3',
'четыре': '4',
'пять': '5',
}
Пишем функцию поиска строки для замены. Единственным аргументом будет объект re.Match.
Используя данные этого объекта мы вычисляем замену on-the-fly!
def get_str(match: re.Match):
word = match.group(1)
return remap.get(word.lower()) or word
Пример текста.
text = '''Раз Два Три Четыре Пять
Вместе будем мы считать
Пять Четыре Три Два Раз
Мы считать научим вас
'''
Теперь запускаем re.sub и вместо строки замены (repl) подаём имя функции.
(Данный паттерн ищет отдельные слова в тексте)
>>> print(re.sub(r'(\w+)', get_str, text))
1 2 3 4 5
Вместе будем мы считать
5 4 3 2 1
Мы считать научим вас
Думаю, достаточно наглядно 🤓
#libs#regex
#Fitness
What Is The Best Diet?
With so many diets out there, it can be confusing to know which one works the best.
Popular ones range from Paleo, Atkins, Vegan, Fruitarian, Ketogenic, gluten-free and other mainstream diets.
So which one is the best?.......Read more
#Fitness
Weighing Yourself
Did you know that your weight depends with the time of the day?
Your bodyweight fluctuates throughout the day, so the scale will display different amounts depending on the time you choose to weigh yourself.
Other factors such as how much you eat and physical activity will cause differences in your weight as the day goes by.
The most accurate time to check your weight is first thing in the morning after urination.
It’s beneficial to weigh yourself at least once a week in order to ensure you are making progress towards your goal.
It isn't necessary to weigh yourself every day, but doing so will help you get a better understanding of the changes in weight based on your balance of calories.
🚨Source : @HeathSafetyTps
✅Share Now
#Fitness
Training Mentality
Determination & Focus. These are the main differences between training and just working out.
“Working out” consists of simply doing exercises without a specific goal in mind.
“Training” demands that you exercise with greater principles that not only make you physically stronger, but also mentally tougher as well.........Read more
#Fitness
Common Mistakes During Training
Did you know that training “smart” means more than just knowing how to use the machines in your gym correctly.
You have to plan critically about your workouts, and make sure everything you do has a specific purpose and will get you closer to your goals.
Here are common mistakes people make when training, and how to fix them.......... Read more
#Fitness
RESTDAY From Gym/Exercises
It is important to occasionally incorporate a full day of rest from training in order to allow your body sufficient recovery.
As training becomes more frequent, your body is at greater risk for injury due to strain on muscles, tendons, ligaments, bones and joints.
Muscle fibers are broken down during weight training, so sufficient time is needed for the body to repair and grow new muscle.
It can be smart to train certain muscles on specific days so you can allow other muscles to recover.
For example, training upper body on one day and lower body on a separate day, allows one muscle group to recover while training another.
Benefits of incorporating a rest day include improvements in training performance, a stronger immune system, and more energy.
If desired, you can remain active during a rest day with light exercise such as jogging, yoga, or stretching.
🚨Source : @HeathSafetyTps
✅Share Now
#Fitness
Central Nervous System (CNS)
The CNC consists of the brain, spinal cord, and a complex network of neurons.
This system is responsible for sending, receiving, and interpreting information throughout all parts of the body.
Your CNS controls every thought and movement in the body, making it extremely important to maintain its health.
Extensive training without sufficient rest increases the risk of damage to your CNS.
Most cells in your CNS cannot be repaired or renewed and can lose some of its abilities.
Signs of damage are difficulty with physical activity, recovering, comprehending information, & other symptoms.
The CNS is at an increased risk for damage while consuming fewer calories than normal, which emphasizes the need for sufficient nutrients and recovery while dieting.
Just like the muscular system, your CNS can be overworked.
With proper nutrition and efficient training you can protect and maintain the health of your CNS
🚨 Source : @HeathSafetyTps
✅Share Now
#fitness
How Do Muscles Grow?
Lifting weights damages your muscles. Though that may sound strange, pumping iron at the gym actually depletes muscle-building nutrients in your body and creates microscopic tears in your muscle fibers.
It is only until after your workout that......... Read more
🚨Source: @HeathSafetyTps
✅ Share Now
#fitness
SUPPLEMENTS
Most people looking to burn fat or gain muscle immediately turn to supplements as if it is needed to achieve great results.
Though supplements can be beneficial, they are only meant to help “supply” your diet and are not needed to reach your goal.
Most of the popular supplements can be acquired from food but it can be convenient to have certain ones available.
With that said, here are some recommended supplements to aid the pursuit of your fitness goal...... Read more
Importance Of Fiber In Your Body
Fiber is the part of plant foods that our bodies can’t digest or absorb.
There are two kinds of dietary fiber, insoluble and soluble.
Soluble fiber comes from......Read More
🚨Source : @HeathSafetyTps
✅ Share Now #fitness