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

Резултати

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

Пребарај: #intermediate

当前筛选 #intermediate清除筛选
English Speakers

@English_Speakers · Post #4542 · 06.05.2021 г., 00:42

#intermediate 📌 made my day Meaning 👉 To cause one to feel very happy; to be a very positive highlight of one's day. Example When my neighbors surprised me with homemade chocolate chip cookies, it is really made my day. @English_Speakers

English Speakers

@English_Speakers · Post #4479 · 17.03.2021 г., 17:59

#Intermediate @English_Speakers 📌 When the cat a way the mice will play غاب القط فالعب يا فار people being supervised often do things they are not supposed to do when the supervising person is not around (expression often used in a humorous way about employer and employees, parents and children, etc.) 👉Example: "“His parents are away for the weekend.” “I see—while the cat's away.” @English_Speakers

New Psychedelics compounds search. Why? Deal with First gen psychedelic issues: - they were not created specifically to threat a particular disorder even if can do it with a certain efficacy - they have cardiotoxicity related to 5ht2b mechanism - long action duration length for therapy New hopes and ideas: - decouple halucenogetic from therapeutic effect - potentially reaching even newer states of mind - targetly engineered experience without so complex set and setting What? - Kanna alcaloids for premature ejaculation 😅 - BPL-003 for Treatment Resistant Depression (TRD). - IHCH-7113 Non halucenogetic psychedelic for depression - Ele-101 for depression and Alcohol Use Disorder (AUD). How? 1. AI assisted search - Predictive AI. Train on structure to properties (need big dataset of both) - Generative AI. Evolutionary machines 2. Natural compounds search and enchantment - Research existing less popular natural compounds rom indigenous communities - Enchance properties (Increase a half life, change blood barrier penetration, etc.. 3. Future approaches - computational chemistry (compounds VS receptors ) - test on brain organoids Skill level: #intermediate https://youtu.be/BQoIozpBU5Y

https://podcasts.google.com/feed/aHR0cHM6Ly9mZWVkcy5saWJzeW4uY29tLzgxODk1L3Jzcw/episode/NjgxMmNkZTUtYThmZi00OWIxLThkMmMtZGU5NGM4MDQ2YjRl?ep=14 Why MDMA analogs? 1. Safer options for mory risky categories of people: People with Cardiac deseas history People over the age of 65 2. Other medical application apart form PTD Social anxiety for Autism Parkinson's desease 3. Other impoovements Shorter therapy duration More cheaper production Skill level: #intermediate

Researchers Are Mapping DMT Dimensions Through DMTx Tech Seems like DMTX is finally started and we will see more exciting news from various labs all over the world. Any friends anesthesiologists?😁 "But that doesn’t mean we can’t have some kind of mapping. One can think about Level mapping for example, so do different levels of intensity experience reliably take you to different types of spaces? Is there a progression? I mean people talk already, about you know, moving to the waiting room and then the dome. There has already been developed in a very informal sense, a certain kind of mapping of the space.” Skill level #intermediate https://psychedelicspotlight.com/researchers-are-mapping-out-new-dimensions-through-dmtx-technology/

English With Natives*

@sirjimmy · Post #31213 · 10.10.2024 г., 05:11

1️⃣How often does he work? Everyday All day Rarely 2️⃣What is he starting to think about? Playing basketball Watching TV His health Work 3️⃣What decision is made to get more exercise? Running or Jogging Doing more outdoor activities Going to the local gym 4️⃣What type of lessons are they considering? Dance Tennis Basketball 5️⃣For $120, How often will they meet? Everyday for a month Once a week for two months Every afternoon Twice a week for one month 6️⃣Please fill the blank and tell me what does whole sentence mean? Playing tennis twice a week will be a good start. ..... me .... . #Listening #Intermediate #Teamjimmy @Sirjimmy

English With Natives*

@sirjimmy · Post #30337 · 19.05.2023 г., 07:30

1️⃣How often does he work? Everyday All day Rarely 2️⃣What is he starting to think about? Playing basketball Watching TV His health Work 3️⃣What decision is made to get more exercise? Running or Jogging Doing more outdoor activities Going to the local gym 4️⃣What type of lessons are they considering? Dance Tennis Basketball 5️⃣For $120, How often will they meet? Everyday for a month Once a week for two months Every afternoon Twice a week for one month 6️⃣Please fill the blank and tell me what does whole sentence mean? Playing tennis twice a week will be a good start. ..... me .... . #Listening #Intermediate #Teamjimmy @Sirjimmy

English With Natives*

@sirJimmy · Post #30259 · 28.04.2023 г., 06:37

1️⃣How often does he work? Everyday All day Rarely 2️⃣What is he starting to think about? Playing basketball Watching TV His health Work 3️⃣What decision is made to get more exercise? Running or Jogging Doing more outdoor activities Going to the local gym 4️⃣What type of lessons are they considering? Dance Tennis Basketball 5️⃣For $120, How often will they meet? Everyday for a month Once a week for two months Every afternoon Twice a week for one month 6️⃣Please fill the blank and tell me what does whole sentence mean? Playing tennis twice a week will be a good start. ..... me .... . #Listening #Intermediate #Teamjimmy @Sirjimmy

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