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

Резултати

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

Пребарај: #experiment

当前筛选 #experiment清除筛选
Language Trivia 🤔

@languagetrivia · Post #528 · 22.12.2024 г., 11:01

🚨Let’s play a little game🚨 🔍Your mission: Write English words in the comments that contain the letter Q. Let’s collect a list of at least 50-70 words. I’ll reveal the purpose of this experiment soon… 🔥 Ready? Go! @languagetrivia#experiment

Hashtags

Language Trivia 🤔

@languagetrivia · Post #547 · 27.12.2024 г., 12:17

🧠 The Stroop Effect Challenge! 👉 Instructions: 1) Read out loud the name of the colors in the top half of the image. 2) Now, in the bottom half say the color of the text, not the word itself. (E.g. for the first word of the bottom part you need to say “green”, because this is the color in which the word is written) This is called the Stroop Effect – a psychological phenomenon where your brain struggles to process conflicting information. Your brain wants to read the word (e.g. "Purple"), but the task is to say the color of the text (e.g. "Green"). This mismatch causes a slight mental slowdown as your brain processes the conflict. Did your brain glitch? Yes 🤯| No 😎 Subscribe to Language Trivia || #experiment#phenomenon

Interesting Planet 🌍

@interesting_planet_facts · Post #873 · 07.10.2025 г., 18:11

🌎 Physicists are searching for evidence of extra dimensions that could exist alongside our three spatial dimensions and time. Experimental efforts, like those at the Large Hadron Collider, look for signs such as missing energy or unusual particle behavior that might indicate the presence of dimensions beyond the familiar four. So far, no direct evidence has been found for extra dimensions. ✨ #physics⚡#dimensions⚡#experiment 👉subscribe Interesting Planet 👉more Channels ​

Language Trivia 🤔

@languagetrivia · Post #518 · 20.12.2024 г., 12:13

🧪 Experiment time! Which of these shapes would you associate with the word 'Bouba,' and which with 'Kiki'? 👀 Check the first comment under the poll below for details about this experiment and what it reveals about human perception! @languagetrivia#experiment#fact#phenomenon

Language Trivia 🤔

@languagetrivia · Post #525 · 21.12.2024 г., 17:12

“Paris in the the spring.” Did you notice the extra “the”? If not, don’t worry – it’s a common perception error! 🔍Why does this happen? The second “the” is often skipped because of how our eyes move while reading. Our brains prioritize speed and smoothness, filling in the blanks as we read. When your eyes jump from “Paris” to “spring”, the brain might overlook the extra “the” in between. 📝 This illusion shows how our minds sometimes trade accuracy for efficiency. [Source] Did you catch the repetition right away 🤓, or did it take a second glance to spot it 🙈? @languagetrivia#illusion#phenomenon#experiment

Language Trivia 🤔

@languagetrivia · Post #561 · 02.01.2025 г., 11:21

🎮 Emoji Idiom Creative Challenge! 🔹Can you come up with an idiom based on these three emojis?🐦⏰🥱 🔹Think creatively explain what it could mean. Go to the comments and have a go, let’s see what you come up with! ✨Like the best idiom and explanation! This way, we can see whose creation stands out the most @languagetrivia#game#challenge#experiment

🔍В 1971 году профессор психологии Филип Зимбардо провел эксперимент в Стэнфордском университете, который получил название «Тюремное заточение». ▪️Этот эксперимент показал, как сильно может повлиять социальная среда на поведение людей. Он также вызвал много вопросов о том, насколько эти результаты могут быть применимы к реальной жизни и вызвал дискуссии о моральной стороне проведения подобных экспериментов. Подробнее о тюремном эксперименте можно узнать в карусели➡️ #ҚҚДИ#KIPD#stanfordprisonexperiment#socialpsychology#research#experiment

🔍1971 жылы психология профессоры Филипп Зимбардо Стэнфорд университетінде «Түрмеге қамау» деп аталатын эксперимент жасады. ▪️Бұл эксперимент адамдардың мінез-құлқына әлеуметтік ортаның қаншалықты әсер ететінін көрсетті. Сондай-ақ осындай эксперименттерді жасаудың моральдық жағы туралы пікірталастар тудырды. Эксперимент туралы толығырақ карусельден оқыңыз➡️ #ҚҚДИ#KIPD#stanfordprisonexperiment#socialpsychology#research#experiment

🔍1963 жылы америкалық психолог Стэнли Милгрэм психологиялық эксперимент жасады. Ол қарапайым адамдарға бұйрық берілсе, кінәсіз адамдарды қаншалықты аяусыз жазалай алатынын анықтауға тырысты. Эксперимент күтпеген нәтижелерді көрсетті. Толығырақ карусельден оқыңыздар➡️ ——— 🔍В 1963 году американский психолог Сэнли Милгрэм провел психологический эксперимент, с помощью которого хотел выяснить, как далеко могут зайти люди, причиняя кому-то боль, если это входит в их обязанности. Результаты эксперимента оказались неожиданными. Подробнее об эксперименте можно узнать в карусели➡️ #ҚҚДИ#KIPD#milgramexperiment#socialpsychology#research#experiment

VERUM - War crimes investigations

@verum_in_english · Post #271 · 20.06.2025 г., 10:42

Realities of War: K9 Units in the Special Military Operation Zone They say a dog is a man’s best friend... I hope this huge German Shepherd without a muzzle is running towards me to check how I’m doing... A dog is not just a loyal companion. In the hands of an experienced K9 handler, it can become a mine detector, an assault unit, or even an FPV drone. During World War II, dogs were used to destroy tanks, often sacrificing their lives. Today, they no longer carry out such deadly missions, but they remain a sudden and formidable weapon on the battlefield. Modern K9 handlers are ready to provide any assistance to their four-legged partners right in the field. Our report from the Brigade Española kennel sheds light on how these dogs are trained and what role they play in the conflict zone. #war#k9units#militarydogs#SMO#minedetectors#army#dogs#man'sbestfriend #experiment#bestfriend Sorry, but there was no stopping our editor: A dog truly is man’s best friend. Don’t believe it? Try this experiment: Lock your wife and your dog in the trunk of your car. Come back in an hour or two. Who do you think will be happier to see you? Want a friend in the family? Get a dog. Want someone to bark at you? Get married.

123•••10•••20•••303132
ПретходнаСтраница 1 од 32Следна