Функция 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
Indiana Officer Resigns After Misusing Clearview AI
An Indiana police officer has resigned after it was discovered he frequently misused Clearview AI’s facial recognition technology to track social media users not linked to any crimes. According to the Evansville Police Department, the officer disguised personal searches by using actual case numbers associated with real incidents.
An audit revealed an unusual high usage of Clearview AI by the officer, who primarily searched social media images rather than live or CCTV footage typically used in investigations. The department recommended termination, but the officer resigned before a final determination could be made.
This incident highlights significant concerns about the misuse of facial recognition technology and underscores the need for stricter oversight and compliance measures to prevent abuse.
#AI#Privacy#FacialRecognition#ClearviewAI
Clearview AI Agrees to Conditional Settlement in Privacy Lawsuit
Clearview AI has reached a unique settlement agreement in a privacy lawsuit involving its data-scraping facial recognition technology. Unable to afford immediate compensation, Clearview AI will establish a fund representing 23% of the company's value as of last September. This fund will only be activated if the company undergoes an IPO or a significant event like a merger or asset sale. Based on Clearview's current valuation, this fund could be worth up to $51.7 million.
The settlement, awaiting final court approval, also includes appointing a special master to demand cash from Clearview or sell settlement rights to third parties, with proceeds going to class members.
Clearview AI has faced multiple lawsuits accusing it of privacy violations, leading to this creative resolution. The company, burdened by mounting legal costs, agreed to this settlement to avoid bankruptcy and provide potential relief to affected individuals.
#Privacy#AI#ClearviewAI#FacialRecognition#LegalTech
Controversial Changes to EU's AI Act Allow Facial Recognition Without Judicial Approval
Hello, everyone! Recent alterations to the AI Act, initially endorsed in December, are stirring controversy as they permit law enforcement to employ facial recognition on recorded video without judicial consent.
German MEP Svenja Hahn decries these last-minute changes, asserting that they undermine civil rights and draw parallels with practices in authoritarian states. The revisions, concluded on December 22, diverge from the initial agreement, which mandated stricter conditions and judicial oversight for facial recognition use.
Critics express concerns about post-facial recognition technology, emphasizing the need for clarity on privacy and oversight. The final text faces scrutiny on January 24, with potential amendments requiring further legislative attention.
#FacialRecognition#AIAct#EuropeanUnion#CivilRights#PrivacyConcerns
FTC bans Rite Aid from using AI facial recognition in stores for 5 years
Hello everybody! The US Federal Trade Commission (FTC) has barred American drugstore giant Rite Aid from utilizing AI facial recognition technology for surveillance purposes over the next five years.
The FTC intervened as Rite Aid allegedly "failed to implement reasonable procedures" in deploying facial recognition across 200 stores over eight years.
Rite Aid's facial recognition system, designed to identify past shoplifters, resulted in numerous false positives. Tens of thousands of individuals were included, often with low-quality images from various sources, leading to unwarranted confrontations and police interventions, disproportionately impacting people of color.
Rite Aid is mandated to delete collected images, algorithms, and related products, notify consumers, enhance data security measures, and provide clear notices regarding any biometric surveillance technology in stores.
Rite Aid, while agreeing to the FTC settlement, expressed fundamental disagreement with the facial recognition allegations. The company halted the technology's use three years prior to the FTC investigation and commits to fortifying information security practices.
#AILaw#PrivacyRights#FacialRecognition#FTC#RiteAid#LegalTech
🇬🇧#UK
#PreCrime
"I WAS MISIDENTIFIED AS SHOPLIFTER BY FACIAL RECOGNITION TECH"
Sara needed some chocolate - she had had one of those days - so wandered into a #HomeBargains store.
"Within less than a minute, I'm approached by a store worker who comes up to me and says, 'You're a thief, you need to leave the store'."
Sara - who wants to remain anonymous - was wrongly accused after being flagged by a facial-recognition system called #Facewatch.
She says after her bag was searched she was led out of the shop, and told she was banned from all stores using the technology.
Facewatch later wrote to Sara and acknowledged it had made an error.
The #MetropolitanPolice in #London say that around one in every 33,000 people who walk by its cameras is misidentified.
But the error count is much higher once someone is actually flagged.
One in 40 alerts so far this year has been a false positive
#AI
#FacialRecognition