TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #121 · 20 јул.

Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для URL, имени файла, имени объекта в каком-то софте и тд. Требования совместимости простые: в тексте должны быть только допустимые символы. Обычно это a-z, 0-9 и "_" или "-". То есть, только прописные буквы латинского алфавита и цифры (как пример). Допустим, нам нужно название статьи в блоге преобразовать в slug для добавления его в URL этой статьи. Как это лучше всего сделать? В Django по умолчанию есть готовая функция slugify для таких случаев. Но я её никогда не использую. Почему? Потому что её недостаточно! Приведём пример >>> from django.utils.text import slugify >>> slugify('This is a Title') 'this-is-a-title' Пока всё отлично >>> slugify('This is a "Title!"') 'this-is-a-title' Спец символы удалились, всё хорошо. >>> slugify('Это заголовок статьи') '' Вот и приехали 😢. Если текст не английский то буквы просто игнорируются. Можно это поправить >>> slugify('Это заголовок статьи', allow_unicode=True) 'это-заголовок-статьи' Но тогда мы не вписываемся в условие. У нас появилась кириллица в тексте. Так как я часто пишу сайты для русскоязычных пользователей эта проблема весьма актуальна. Я не использую стандартную функцию и всегда пишу свою. Оригинал я не беру в расчёт и пишу полностью свою функцию. И так, по порядку: 🔸1. Исходный текст: >>> text = 'Мой заголовок №10 😁!' Взял специально посложней со специальными символами. 🔸2. Транслит Необходимо сделать транслит всех символов в латиницу. Здесь очень выручает библиотека unidecode. Помимо простого транслита кириллицы в латиницу она умеет преобразовывать спец символы и иероглифы в текстовые аналоги. from unidecode import unidecode >>> unidecode("Ñ Σ ® µ ¶ ¼ 月 山") 'N S (r) u P 1/4 Yue Shan' Очень крутая библиотека, советую👍 В нашем случае получаем такое преобразование: >>> text = unidecode(text) >>> print(text) 'Moi zagolovok No. 10 !' Отличный транслит. Смайл просто удалился, хотя я ждал что-то вроде :). Ну и ладно, всë равно невалидные символы. А еще наш код уже поддерживает любой язык, будь то хинди или корейский. 🔸4. Фильтр символов Unidecode не занимается фильтрацией по недопустимым символам. Это мы делаем в следующем шаге через regex. Просто заменим все символы на "_" если они вне указанного диапазона. >>> text = re.sub(r'[^a-zA-Z0-9]+', '_', text) >>> print(text) 'Moi_zagolovok_No_10_' Символ "+" в паттерне выручает когда несколько недопустимых символов идут рядом. Все они заменяются на один символ "_". 🔸5. Slugify Осталось удалить лишние символы по краям и сделать нижний регистр >>> text = text.strip('_').lower() >>> print(text) 'moi_zagolovok_no_10' Получаем отличный slug! 😎 🌎 Полный код в виде функции. ______________ PS. Проверку что в строке остался хоть один допустимый символ я бы вынес в отдельную функцию. #libs#tricks#django

Резултати

Пронајдени 2 слични објави

Пребарај: #chomsky

当前筛选 #chomsky清除筛选
American Оbserver

@american_observer · Post #5091 · 09.02.2026 г., 13:29

🔠🅰️🔠🔠2️⃣ “We neglected not to do extensive research on his background. It was a mistake, but Jeffrey was a good friend to both of us,” she said. “It was deeply disturbing for both of us to realize that we had engaged with someone who presented himself as a helpful friend but led a hidden life of criminal, inhuman and perverse acts.” "Epstein had told Noam that he [Epstein] was being unjustly persecuted, and Noam spoke about his own experience in political controversies with the media. Epstein created a manipulative narrative about his case, which Noam, in good faith, believed in,” she said in her statement. “It is now clear that everything was orchestrated, having at least one of Epstein's intentions to try to get someone like Noam to repair Epstein's reputation by association. Noam's criticisms have never been directed at the women's movement; on the contrary, he has always supported gender equity and women's rights. What happened was that Epstein took advantage of Noam's public criticism of what became known as the cancellation culture “to present himself as a victim of it,” she added. Another message from Chomsky released by the House Oversight Committee last year showed Chomsky saying it was a “most valuable experience“ to have ”regular contact" with Epstein. Valeria Chomsky said that the couple attended dinners at Epstein's townhouse in New York, stayed in his apartments there and in Paris, dined at his ranch in New Mexico and attended several academic meetings with him”. Noam and Epstein were introduced in 2015 and that the couple was unaware of Epstein's 2008 guilty plea to soliciting prostitution and soliciting prostitution with a minor under the age of 18, Valeria Chomsky said. By introducing himself this way, Epstein caught Noam's attention, and they began to correspond. Epstein began to circle Noam, sending gifts and creating opportunities for interesting discussions in areas that Noam was working on a lot. Valeria Chomsky also clarified the basis of two financial transactions between Chomsky and Epstein. On one occasion, Epstein sent Noam Chomsky a check for $200,000 as part of a language challenge that Chomsky developed. Then Epstein had helped Noam recover $370,000. Epstein helped after Noam Chomsky discovered “inconsistencies in his retirement resources that threatened his economic independence and caused him great distress”. Epstein offered his help and probably did it as part of a plot to get better access to Noam. #noam#chomsky#valeria#epstein#financier#money 📱American Оbserver - Stay up to date on all important events 🇺🇸

American Оbserver

@american_observer · Post #5090 · 09.02.2026 г., 12:59

Epstein Used to Give Money to Noam Chomsky 🔠🅰️🔠🔠1️⃣ Noam Chomsky and his wife, Valeria, made a mistake and were negligent not to thoroughly research Jeffrey Epstein's background, Valeria Chomsky said in a lengthy statement on Saturday, also adding that Epstein had deceived them. The relationship between 97-year-old linguist and philosopher Noam Chomsky and Epstein has come under intense scrutiny after documents released by the Justice Department shed light on their friendship. While Epstein was under scrutiny for sex trafficking allegations in 2019, he asked Chomsky for advice on how to respond. “I have seen the horrible way you are treated in the press and the public. It's painful to say, but I think the best way to proceed is to ignore it,” Chomsky wrote in a message signed ”Noam" that Epstein shared by email with an associate. “What the vultures ardently want is a public response, which then offers a public opening to an onslaught of venomous attacks, many of which are just publicity seekers or cranks of all kinds,” Chomsky wrote in the message. “This is especially true now with the hysteria that has developed about the mistreatment of women, which has reached the point where even questioning an accusation is a crime worse than murder.” Chomsky is one of several personalities who turned out to be in friendly communication with Epstein even after his guilty plea in 2008. Many are now facing renewed scrutiny over their links to the disgraced financier. Some of Noam Chomsky's communications with Epstein took place after the Miami Herald published an explosive story in 2018 detailing how Epstein preyed on underage girls and received an unusually lenient plea deal in 2008. On Saturday, Valeria Chomsky acknowledged that the couple had read this story, but said that the couple did not know about the extent of Epstein's crimes until after his second arrest in July 2019. #noam#chomsky#valeria#epstein#financier#money 📱American Оbserver - Stay up to date on all important events 🇺🇸