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 слични објави

Пребарај: #vaccine

当前筛选 #vaccine清除筛选
Reuters: World

@reutersworldchannel · Post #149347 · 14.10.2021 г., 10:07

Australia's Victoria to end lockdown amid case surge Melbourne will exit months of COVID-19 lockdown next week helped by a faster-than-expected vaccine uptake, Victoria state Premier Daniel Andrews said, ahead of schedule even though daily infections hit a record the same day. #News#Reuters#COVID#Vaccine Subscribe: http://smarturl.it/reuterssubscribe Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled. Get the latest news on: http://reuters.com/ Follow Reuters on Facebook: https://www.facebook.com/Reuters Follow Reuters on Twitter: https://twitter.com/Reuters Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en ➖@reutersworldchannel➖

Reuters: World

@reutersworldchannel · Post #149426 · 15.10.2021 г., 19:00

U.S. to lift curbs for vaccinated foreign travelers The United States will lift COVID-19 travel restrictions for fully vaccinated foreign nationals effective November 8, a move that was hailed by the country’s allies #News#Reuters#Vaccine#AirTravel#USA Subscribe: http://smarturl.it/reuterssubscribe Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled. Get the latest news on: http://reuters.com/ Follow Reuters on Facebook: https://www.facebook.com/Reuters Follow Reuters on Twitter: https://twitter.com/Reuters Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en ➖@reutersworldchannel➖

蛋挞报

@Pincongessence · Post #2535 · 19.01.2022 г., 15:10

疫情期间新冠疫苗以前所未有的速度问世。纽约时报做了一篇关于mRNA疫苗的报道,作者把成功归因于三个要素: 1. 艾滋病疫苗的大规模研发 2. mRNA的发现 3. 遗传分子保存技术的突破 而这篇文章的内容,就是围绕这三个要素所展开的科学家们的故事。 Halting Progress and Happy Accidents: How mRNA Vaccines Were Made|原文 #疫情#疫苗#vaccine#science

REACH

@reachsg · Post #672 · 06.06.2021 г., 06:14

Are you considering taking Sinovac through the special access route or have concerns about it? 💉 We would like to know what you think! Head over to our 💻e-Listening Point today to make sure that your views on Sinovac are heard! https://go.gov.sg/vacc-sinovac#EveryVoiceMatter#REACHsg#Covid19#vaccine

Reuters: World

@reutersworldchannel · Post #149323 · 13.10.2021 г., 18:19

COVID-19 shot requirements boosting vaccine rates, White House says Vaccination rates against COVID-19 in the U.S. have risen by more than 20 percentage points after multiple institutions adopted vaccine requirements, White House COVID-19 response coordinator Jeff Zients said. #vaccine#COVID#JeffZients#News#Reuters Subscribe: http://smarturl.it/reuterssubscribe Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled. Get the latest news on: http://reuters.com/ Follow Reuters on Facebook: https://www.facebook.com/Reuters Follow Reuters on Twitter: https://twitter.com/Reuters Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en ➖@reutersworldchannel➖

Reuters: World

@reutersworldchannel · Post #149442 · 16.10.2021 г., 04:54

Dutch develop no-pain needle-free injections Researchers in the Netherlands are developing ‘virtually painless’ injections without needles in what they hope is a breakthrough that will ease fear and encourage vaccinations #News#Reuters#BubbleGun#NeedleFree#Vaccine Subscribe: http://smarturl.it/reuterssubscribe Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled. Get the latest news on: http://reuters.com/ Follow Reuters on Facebook: https://www.facebook.com/Reuters Follow Reuters on Twitter: https://twitter.com/Reuters Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en ➖@reutersworldchannel➖

Reuters: World

@reutersworldchannel · Post #149294 · 13.10.2021 г., 08:24

American Airlines, Southwest stand by vaccine mandate Rebuffing the Texas governor, American Airlines and Southwest Airlines said they would comply with U.S. President Joe Biden's executive order to require that their employees be vaccinated for COVID-19 by a Dec. 8 deadline. #News#Reuters#Texas#Airlines#COVID#Vaccine Subscribe: http://smarturl.it/reuterssubscribe Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled. Get the latest news on: http://reuters.com/ Follow Reuters on Facebook: https://www.facebook.com/Reuters Follow Reuters on Twitter: https://twitter.com/Reuters Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en ➖@reutersworldchannel➖

NIDO Russia (НИДО)

@nido_russia · Post #1930 · 22.12.2024 г., 19:16

A Nigerian 🇳🇬 former bricklayer now turned medical doctor leads a team that developed the World’s first ever potent Cancer Vaccine in Russia 🇷🇺 Thumbs up 👍🏿 to the export from Africa's most populous Nation. Nigeria to the World! Nigeria & Russia will succeed. https://t.me/nido_russia/1930 #medicine#health#vaccine#cancer#nido#NidoRussia

Reuters: World

@reutersworldchannel · Post #149385 · 15.10.2021 г., 01:15

FDA advisers back Moderna booster shots for some A panel of expert advisers to the U.S. FDA unanimously voted to recommend booster shots of Moderna’s COVID-19 vaccine for Americans aged 65 and older and those at high risk of severe illness or occupational exposure to the virus. #COVID19#boostershot#Moderna#vaccine#News#Reuters Subscribe: http://smarturl.it/reuterssubscribe Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled. Get the latest news on: http://reuters.com/ Follow Reuters on Facebook: https://www.facebook.com/Reuters Follow Reuters on Twitter: https://twitter.com/Reuters Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en ➖@reutersworldchannel➖

Reuters: World

@reutersworldchannel · Post #149396 · 15.10.2021 г., 10:46

Biden meets Kenyan President Uhuru Kenyatta President Joe Biden told visiting Kenyan President Uhuru Kenyatta that the United States will make a one-time donation of more than 17 million doses of the Johnson & Johnson vaccine to the African Union. #News#Reuters#JoeBiden#UhuruKenyatta#COVID#vaccine Subscribe: http://smarturl.it/reuterssubscribe Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled. Get the latest news on: http://reuters.com/ Follow Reuters on Facebook: https://www.facebook.com/Reuters Follow Reuters on Twitter: https://twitter.com/Reuters Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en ➖@reutersworldchannel➖

Reuters: World

@reutersworldchannel · Post #149296 · 13.10.2021 г., 10:27

FDA declines to take stance on Moderna boosters U.S. FDA researchers said Moderna's COVID-19 vaccine did not yet meet the guidelines for booster shots #News#Reuters#FDA#Moderna#Vaccine#BoosterShot Subscribe: http://smarturl.it/reuterssubscribe Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled. Get the latest news on: http://reuters.com/ Follow Reuters on Facebook: https://www.facebook.com/Reuters Follow Reuters on Twitter: https://twitter.com/Reuters Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en ➖@reutersworldchannel➖

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