Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> text = '''
>>> Alex:8999123456
>>> Mike:+799987654
>>> Oleg:+344456789
>>> '''
Соответственно, для выделения нужных элементов будем использовать группы. Получится такой паттерн:
(\w+):([\d+]+)
Как мы будем формировать словарь из найденных групп?
>>> import re
>>> results = []
>>> for match in re.finditer(r"(\w+):([\d+]+)", text):
>>> results.append({
>>> "name": match.group(1),
>>> "phone": match.group(2)
>>> })
>>> print(results)
[{'name': 'Alex', 'phone': '8999123456'}, ...]
Можно немного сократить запись используя zip
>>> results = []
>>> for match in re.finditer(r"(\w+):([\d+]+)", text):
>>> results.append(dict(zip(['name', 'phone'], match.groups())))
Но есть способ лучше! Это именованные группы в regex. Можно в паттерне указать имя группы и результат сразу забрать в виде словаря.
>>> for match in re.finditer(r"(?P<name>\w+):(?P<phone>[\d+]+)", text):
>>> results.append(match.groupdict())
То есть всё что я сделал, это добавил в начале группы (внутри сбокочек) такую запись:
(?P<group-name>...)
Теперь найденная группа имеет имя и можно обратиться к ней как к элементу списка
>>> name = match['name']
Либо забрать сразу весь словарь методом groupdict()
>>> match.groupdict()
#tricks#regex
#BlackFriday#Aliexpress
M17 Handheld #VideoGame Console 64G 128G Open Source Linux System 4.3inch Screen Portable Pocket Video Player Retro Gaming Conso
Price 28.30€
Place your order
https://s.click.aliexpress.com/e/_EzGbfbR
Chinese state media wants gaming loopholes closed
Chinese state media said loopholes allowing minors to bypass new rules aimed at curbing gaming play time to three hours per week should be removed to 'prevent addiction.'
#News#Reuters#China#VideoGame
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➖
Some of us prefer to have some fun while also learning new things about our favorite subjects😎
#videogame#privacy#fun#security
So, in this post, we recommend three video games that are fun, but also help you learn a lot about data privacy, cybersecurity, and related topics💻
🔢Hacknet: A famous hacker known as "Bit" has died, and you must investigate his death. Released in 2015, this game teaches you about real-world hacking techniques and cybersecurity principles. You learn to navigate networks, analyze data, and see the importance of data privacy.
🔢Orwell: It's a narrative-driven game in which you are a government operative who monitors citizens' data to prevent crime. The game raises questions about privacy, surveillance, and the ethical implications of data collection.
🔢Cybersecurity Lab: This game is designed for students, and it puts them in engaging scenarios and challenges to teach them about cybersecurity concepts, including data privacy.
Hope you have a lot of fun playing these. Best wishes🌹
🆔Privacy
Alla ricerca di un qui ed un ora dalla forma conveniente per quanto ridotta all'osso.
#vaporonda#vaporwave#vapourwave#vaporart#seapunk#webpunk#glitch#glitchart#glitchartistscollective#chillwave#aesthetic#vaporwaveaesthetic#vaporwaveaesthetics#malinconia#melancholy#tristezza#sadness#sadboy#lofi#testaccio#mattatoio#videogioco#videogame#undertale#undertalesans#sans