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

Резултати

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

Пребарај: #bigpharma

当前筛选 #bigpharma清除筛选

👇🧐 Sûr et Efficace ⁉️ Nous savons maintenant qu'il n'en est rien. Le risque de décès est bien plus élevé chez les personnes vaccinées que chez les non vaccinées. #BigPharma empoisonne nos enfants afin d'avoir un vivier d'humains malades à vie, vivant sous la tutelle de l'industrie pharmaceutique. La priorité de #BigPharma est et sera toujours l’enrichissement. Les bénéfices pour eux, les risques pour vous. N'oubliez pas l'adage de #BigPharma : Un patient guéri est un client perdu. Un patient malade est une rente à vie. 🔗👇🔗 https://vaccinechoicecanada.com/riskofdeath/

Hashtags

Man in America 🇺🇸

@maninamerica · Post #2805 · 31.01.2025 г., 23:25

My friend @drdrew asks a legit question here? Why the double standard? We all throw a fit about it every time a doctor takes anything from big pharma but no one cares about our politicians being bought off entirely. #BigPharma 🪓@AttorneyThomas

Hashtags

BadVolf

@BadvolfNews · Post #580 · 28.03.2023 г., 09:34

❗️How things might look in a more just world. All are equal before the law - but some are more equal than others. #Democrats#BigPharma Share and subscribe to American Majority

Martina Pastorelli

@mpastorelli · Post #2461 · 26.05.2024 г., 20:33

BREAKING : #BigPharma is in the hands of worthless people who now control the #WHO. Ethics, science and health don't matter: only money matters. The covid vaccine has caused many deaths but the media is subservient We broke mainstream news in Italy 🔥 Via La Verita newspaper @AseemMalhotra

Man in America 🇺🇸

@maninamerica · Post #2798 · 30.01.2025 г., 01:50

Billionaire Nicole Shanahan Puts Senate on Notice — “Dear U.S. Senators, Bobby may play nice; I won’t." The overwhelming support for RFK Jr.’s confirmation is just incredible. We The People are wide awake and will no longer allow #BigPharma to play their games. #MAHA#RFKJr

Man in America 🇺🇸

@maninamerica · Post #2804 · 31.01.2025 г., 20:54

Shocking Truth: Oncologists BANNED from Discussing Cheap Cancer Cures? 🚨 The truth about cancer treatment: Drugs like Ivermectin and Fenbendazole, which are off patent and dirt cheap, are off limits for discussion. Oncologists at top tier hospitals like MD Anderson and Johns Hopkins can't even mention them, despite peer-reviewed evidence supporting their use. Why? Because Big Pharma dictates what treatments are 'allowed.' Patients are turning to me for alternatives because the system is broken. Time to question the status quo in cancer care. Your life might depend on it. Share if you support the right to know about all cancer treatment options! #Cancer#BigPharma#ManInAmerica

Egountchi Behanzin Officiel

@egountchibehanzinofficiel · Post #7909 · 24.12.2024 г., 16:49

⚠️🦠‼️☢️ TERRORISME SANITAIRE ET BIOLOGIQUE de la fondation Bill Gates, de l’armée américaine (#DARPA) et de #BigPharma en #Afrique. 🔸#BillGates est devenu le principal financeur des vaccins RTS,S antipaludique tueurs de jeunes filles africaines et expérimentations dangereuses de génie génétique menées sur des cobayes en Afrique, ( Burkina Faso 🇧🇫, Djibouti 🇩🇯, Kenya 🇰🇪 ) etc… notamment sur les gènes du maïs et du manioc, ainsi que sur la modification génétique des moustiques OGM. 🔹Officiellement intransigeante sur les OGM en raison des risques potentiels pour la santé et l'environnement, l’Union européenne finance pourtant les fonds privés créés par l’eugéniste milliardaire américain pour développer en Afrique ce qu’elle interdit sur son territoire. POURQUOI ? REJOIGNEZ LA RÉSISTANCE SUR lTELEGRAM. 🔺Pour les numéros français : https://t.me/egountchibehanzinTV 🔻Pour les numéros internationaux : https://t.me/EgountchiBehanzinOfficiel @egountchibehanzinTV

Egountchi Behanzin Officiel

@egountchibehanzinofficiel · Post #8131 · 06.02.2025 г., 07:03

#SouverainetéSanitaire#Santé#BillGates#BigPharma Il est temps que les pays africains, dans leur lutte pour la souveraineté, se retirent de l'Organisation mondiale de la santé (OMS), actuellement prise en otage par Bill Gates. Sincèrement, cela est nécessaire, sauf si les dirigeants sont complices de ce terrorisme scientifique, chimique et biologique de cette organisation à l'encontre des populations africaines. @egountchibehanzinTV

Egountchi Behanzin Officiel

@egountchibehanzinOfficiel · Post #7025 · 18.08.2024 г., 09:36

☢️🦠❌#SANTÉ | Face au terrorisme sanitaire et scientifique des firmes américano-européennes en #Afrique, la pharmacovigilance censée protéger la santé des populations africaines est défaillante en raison de la complicité des dirigeants africains soumis et corrompus par les firmes pharmaceutiques (#BigPharma), #FondationBillGates, #Gavi appartenant aux États impérialistes occidentaux. Il est donc essentiel que nous alertions et sensibilisions directement les Africains sur ces pratiques inacceptables afin de dénoncer les mensonges et la guerre économique qui sont devenus des armes de désinformation utilisées pour manipuler les populations et les inciter à utiliser des produits sans être informées des risques et effets des vaccins.#EB Telegram: @egountchibehanzinTV

Daniel Prinz News

@DanielPrinzOffiziell · Post #9972 · 21.01.2026 г., 09:01

‼️Die investigative Journalistin Whitney Webb: „Die Leute tun gerne so, als sei die Eugenik verschwunden, aber das ist sie nicht. Sie hat nur einen neuen Namen bekommen.“‼️ „Sie stellen es als Gesundheitsfürsorge dar, aber es ist Eugenik, die als Gesundheitsfürsorge dargestellt wird. Und leider hat Covid einen Präzedenzfall geschaffen, in dem es obligatorisch sein kann ... in dem man seinen Lebensunterhalt verlieren kann ... nicht mehr reisen kann.“ Quelle:Wide Awake Media Findest du diese Info wichtig? Dann abonniere unseren Kanal! 👉@LegitimNews #Eugenik#GreatReset#Covid19#BigPharma#ZweiKlassenGesellschaft#Sklavenrasse#Menschenupgraden

12
ПретходнаСтраница 1 од 2Следна