Функция 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
🚨🇺🇸MICROSOFT AI INVESTMENTS TRIGGER MASSIVE TECH SELLOFF FEARS
🔹 MSFT crashes 15% YTD to $410 after revealing $37.5B AI capex spending — Wall Street panicking over return on investment timeline 💰📉
🔹 Tesla faces March 9 NHTSA compliance deadline for 2.88M FSD vehicles — potential $139M penalty sparks 2% pre-market drop to $388 🚗⚡
🔹 Software sector hemorrhages $800B as S&P Software Index plunges 13% in February — biggest tech rotation since 2002 dot-com crash 💸
Silicon Valley's AI gold rush hitting reality wall — investors fleeing to consumer staples as tech's worst quarter since 2008 unfolds 🤔💥
#TechStocks#USNews
@america
📈Volatility Log: Skew Says Tech Stocks and Europe Rates Aren't Done
Despite seemingly calm spot markets, the volatility log reveals persistent hedging demand driven by intertwining macro catalysts including key tech stocks and European inflation trends. We examine...
🔗Read Full Analysis
🎯 SPECIAL OFFER: 15% OFF
💸 Coupon Code: salenow15%
🚀 Upgrade to premium signals → https://markets.fxpremiere.com/en/signals?utm_source=telegram
📰 Stay ahead — get breaking financial news & analysis at https://markets.fxpremiere.com/en?utm_source=telegram
#Volatility#TechStocks#InterestRates
🚀 Hong Kong Stocks Open Lower as Tech Shares Decline
Hong Kong stocks opened lower today, with the Hang Seng Index dropping 0.71% and the Hang Seng Tech Index falling 0.69%. According to Jin10, technology stocks led the decline, with Baidu (09888.HK) down over 3% and NetEase-S (09999.HK) falling more than 2%.
#HongKongStocks#HangSengIndex#HangSengTechIndex#TechStocks#Baidu#NetEase
🚀 STOCKS | Hong Kong's Hang Seng Index Retreats After Previous Surge
On April 9, Hong Kong's Hang Seng Index experienced a pullback following a significant rise of nearly 800 points the previous day. According to Jin10, the index opened over 100 points lower in the morning and briefly fell more than 200 points to reach 25,653.63 points before recovering slightly. By midday, the Hang Seng Index closed down 0.35% at 25,803.12 points, while the Hang Seng Tech Index fell 1.26% to 4,861.39 points. The total market turnover for the Hang Seng Index reached HKD 126.652 billion.
In terms of sector performance, optical communication and computing infrastructure stocks led gains, while the innovative drug concept saw a brief surge in early trading. However, most technology stocks underwent a correction, with real estate and gold stocks experiencing notable declines. Among individual stocks, Yangtze Optical Fibre and Cable Joint Stock Limited Company (06869.HK) rose 3.2%, WuXi AppTec Co., Ltd. (02359.HK) increased by 3.53%, Kingdee International Software Group Company Limited (00268.HK) fell 5.49%, Kuaishou Technology (01024.HK) dropped 3.55%, and Longfor Group Holdings Limited (00960.HK) decreased by 4.07%.
#HangSengIndex#HongKongStocks#StockMarket#TechStocks#RealEstate#Gold#MarketPullback#Trading#Investment
🚀 Lumentum Holdings Sees 132% Return Amid Nvidia's $2 Billion Investment
Lumentum Holdings has experienced a remarkable 132% return this year, transforming a $1,000 investment in January into $2,320 by April. According to NS3.AI, this impressive rally is attributed to Nvidia's substantial $2 billion acquisition of ultra-high-power lasers and capacity rights for next-generation optical interconnects. The strategic move by Nvidia has significantly boosted investor confidence in Lumentum Holdings, driving its stock performance upward.
#LumentumHoldings#Nvidia#Investment#StockMarket#TechStocks#OpticalInterconnects#InvestorConfidence#HighReturn
Exodus Debuts on NYSE with 36% Gain
Exodus, a developer of non-custodial software, made its debut on the New York Stock Exchange (NYSE) under the ticker EXOD. In its first trading session, shares surged 36%, bringing the company's market capitalization to $1.4 billion. For more details, visit ForkLog.
#Exodus#NYSE#IPO#StockMarket#Investing#Growth#TechStocks#FinancialNews#Blockchain#Software#NonCustodial#MarketCapitalization#Trading#WallStreet
DeepSeek AI Disrupts Tech and Crypto Markets
DeepSeek, a Chinese AI startup, launched its DeepSeek-R1 model, rivaling OpenAI's offerings but at significantly lower costs. The buzz around DeepSeek has led to a $1 trillion drop in US tech stocks, with Nvidia shares tumbling nearly 10%. Experts caution against hasty conclusions regarding the market reaction. Amidst this, investment director Michael van de Poppe advises Ethereum investors to stick to long-term strategies, predicting positive growth for Ethereum and Solana in 2025 due to lower interest rates and geopolitical instability. Read more about the implications of DeepSeek's emergence on the tech landscape here.
#AI#DeepSeek#Crypto#Ethereum#Solana#TechStocks#Nvidia#MarketCrash#Investing#Finance#Web3#MachineLearning#ArtificialIntelligence#Startups#China#Innovation#Stocks#HedgeFund#DeFi#Trends#MarketTrends