Функция 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
#вакансия#vacancy#DA#analyst#senior#remote#fulltime#optimization
Вакансия: Middle+/Senior Data Analyst (с опытом в оптимизационных задачах)
Формат: Удалённый
Занятость: Полная
Оплата: 3500 - 4500$ net.
Ptolemay - аутсорсинговая IT-компания полного цикла по разработке мобильных и веб-приложений для бизнеса и стартапов. Ищем ML Engineer для аутстафф-проекта в сфере металлургии.
Обязанности:
- Разрабатывать и внедрять алгоритмы оптимизации для объемно-календарного планирования.
- Осуществлять постановку и решение задач LP, NLP, определять целевые функции и ограничения.
- Автоматизировать планирование в промышленности или смежных областях.
- Работать с пакетами оптимизации (SciPy, Pyomo, CVXPY, OptaPlanner) и солверами (COBYLA, Ipopt и др.).
Требования:
- Опыт работы по функциональному направлению от 4-х лет.
- Знание языков программирования Python либо Java.
- Знание основных типов оптимизационных задач (LP, NLP и т.д.).
- Опыт работы с пакетами оптимизации (SciPy, Pyomo, CVXPY, OptaPlanner или аналогичные).
- Опыт работы с различными солверами (COBYLA, Ipopt и другие), понимание принципов их работы (сильные и слабые стороны).
- Опыт линеаризации задач, постановка целевой функции и ограничений.
- Опыт постановки задачи, разбиение на подзадачи.
Условия работы:
- Удалённый формат работы.
- Полная занятость.
- Оформление по ИП, СМЗ.
- Оплата 3500 - 4500$ net.
Буду рад ответить на вопросы и ознакомиться с резюме: @Dmitriy_Ptolemay
BuyerCaddy Secures $1.5M Funding
BuyerCaddy has successfully raised $1.50M in funding as of December 19, 2024. The platform focuses on cost savings, optimization, and tech stack benchmarking, helping users identify redundant products, track utilization, and enhance integrations.
#Funding#BuyerCaddy#TechStack#Optimization#CostSavings
Ekore Secures $1.35M Funding
Ekore raised $1.35M in funding, set to enhance building management through optimized consumption and maintenance via the Digital Twin concept. For more information, visit Ekore.
#Ekore#Funding#DigitalTwin#BuildingManagement#Optimization
#python#agents#document_search#evaluation#guardrails#llms#optimization#prompts#rag#vector_stores
Ragbits is a tool that helps build and deploy GenAI applications quickly. It offers features like swapping between many language models, ensuring safe interactions with these models, and connecting to various data storage systems. Ragbits also includes tools for managing data and testing prompts, making it easier to develop reliable AI applications. This helps users create more accurate and efficient AI systems by integrating the latest data and reducing errors. Overall, Ragbits makes it faster and more efficient to develop and deploy AI applications.
https://github.com/deepsense-ai/ragbits
#java#aerospace#flight_simulator#java#modeling#optimization#rocket#rocketry#simulation#trajectory
OpenRocket is a free tool to design, visualize in 3D, and simulate model rockets with six-degree-of-freedom flight analysis, real-time data on altitude/velocity, automatic optimization, and exports for 3D printing or other programs. It works on any platform via Java. You benefit by testing rockets virtually first, saving time/money on failed builds, predicting performance accurately, and flying safer, higher with optimized designs.
https://github.com/openrocket/openrocket
Future of AI Search Optimization
A new market emerges as users shift from traditional Google searches to AI tools like ChatGPT and Claude. The $70 billion search optimization industry sets the stage for a vast new optimization market focused on AI responses. Early entrants can capitalize on this shift with relatively simple platforms. Discover more: Read Here
#AI#SearchOptimization#ChatGPT#Claude#Perplexity#MarketTrends#Innovation#TechIndustry#BusinessOpportunities#DigitalMarketing#InformationRetrieval#Technology#Entrepreneurship#FutureOfWork#Investment#Strategy#Growth#Optimization#Startups
#python#ant_colony_algorithm#artificial_intelligence#fish_swarms#genetic_algorithm#heuristic_algorithms#immune#immune_algorithm#optimization#particle_swarm_optimization#pso#simulated_annealing#travelling_salesman_problem#tsp
You can use scikit-opt, a Python library offering many heuristic optimization algorithms like Genetic Algorithm, Particle Swarm Optimization, Simulated Annealing, Ant Colony, Immune Algorithm, and Artificial Fish Swarm Algorithm. It supports user-defined functions to customize operators, allows continuing runs from previous iterations, and accelerates computations via vectorization, multithreading, multiprocessing, and caching. GPU support is in development. It helps solve complex optimization problems such as function minimization and the Traveling Salesman Problem efficiently, with easy installation and rich examples. This saves you time and effort in implementing and tuning optimization algorithms yourself.
https://github.com/guofei9987/scikit-opt