Небольшой трик с регулярными выражениями который редко вижу в чужом коде.
Допустим, вам нужно распарсить простой текст и вытащить оттуда пары имя+телефон. Вернуть всё это надо в виде списка словарей. Возьмем очень простой пример текста.
>>> 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
¡New build available!
#DerpFest | #Official#diting
Device:Xiaomi 12T Pro | Redmi K50 Ultra
Sha256SUM:fcc1f00c1b95a94db388c5acadbb
Build Date:2024-02-22
Downloads:
Link |Mirror
Changelog:
- Reimplement Custom headers feature from Bootleggers
- Allow to skip confirmation in biometric auth dialog
- Tint app name in notifications with app icon color
- Extend showing Ambient instead of fully waking to single tap gesture
- Fix wakeup and long-press actions of assistant key
- Gesture nav: Remove timeout setting and minor improvements
- Few layout fixes for advanced reboot options
- Add faster qs tile animation speeds
- Fix premature short-circuit on end spring anim
- Fix crash on notification icon contrast calculation
- Upgrade blobs to HyperOS CN miui_DITING_OS1.0.24.1.8.DEV_8704513c97_14.0
- adjust vibration
- upgrade kernel and modules to OS1.0.2.0.ULFCNXM Thnks to @Mohammadnt96
Notes
• Gapps are included
• Remebering, Don't report bugs without logs.
• CTS pass by default
By @TeamMEX_XDA
Donate PayPal
¡New build available!
#DerpFest | #Official#diting
Device:Xiaomi 12T Pro | Redmi K50 Ultra
Sha256SUM:1ec96f10def7980fae0eb6ed2af22900e4c5138dc70a612e7c5d89fcbb0a2a48
Build Date:2024-02-03
Downloads:
Link |
Changelog:
- Fixed miui camera issues (Still cant be open photos from the app use google photos)
- Implement UDFPS animations (inside theme picker -> lockscreen)
- Adjust udfps size
- fix issue where rebooting to twrp or similar the device panics to fastboot
- Fixed eSIM issues (now eSIM should work without more problems)
- Implement parallel space
- sync more stuff from derp
- Change vibration effects thnks to
@Mohammadnt96
Notes
• Gapps are included
• Remebering, Don't report bugs without logs.
• CTS pass by default
By @TeamMEX_XDA
Donate PayPal
¡New build available!
#DerpFest | #Official#diting
Device:Xiaomi 12T Pro | Redmi K50 Ultra
MD5SUM:97bed4a62116ae1abcf4211b3ac9a5a2
Build Date:2023-12-20
Downloads:
Link |
Changelog:
- Merge QPR1 (aka December security patch)
- Remove OOS style clear all button toggle due to QPR1 conflicts
- Switch to Yaap's impl for battery icon customizations
- Switch to AOSP themepicker to fix wallpaper apply button and other small issues
- Add DerpFest Updater (based on Lineage updater)
- Fix for Faceunlock needing a reboot to work after registering a face model
- Add optional bouncer user switcher toggle
- Add option to display data disabled indicator icon
- DerpSpace: Add a secure section to quick settings
- DerpLauncher:Import Lawnicons
- Update Gramophone prebuilt
- Switch to ARMv9 and Cortex-A510 optimizations
- Sepolicy enforcing
Notes
• Gapps are included
• FOD Not working on gtx8_spi touch screen
• Remebering, Don't report bugs without logs.
• CTS pass by default
By @TeamMEX_XDA
Donate PayPal
¡New build available!
#DerpFest | #Official#diting
Device:Xiaomi 12T Pro | Redmi K50 Ultra
MD5SUM:5b8c26aeef4d9f418db9c4cbdfe48833
Build Date:2023-11-25
Downloads:
Link |
Changelog:
- Fixed performance degradations
- Fixed dolby atmos issues
- Update props from stock
- Reset FOD blobs to DITING_V14.0.10.0.TLFCNXM
- Dont allow to run foreground process con CPU7
Notes
• Gapps are included
• FOD Not working on gtx8_spi touch screen
• Remebering, Don't report bugs without logs.
By @TeamMEX_XDA
Donate PayPal
¡New build available!
#DerpFest | #Official#diting
Device:Xiaomi 12T Pro | K50 Ultra
MD5SUM:166b3c96ba79207e8e2295621661c3aa
Build Date:2023-11-22
Downloads:
Link |
Changelog:
- FOD issue should be fixed now
- fixed battery styles
- now fod is called again biometrics and not pixel imprint
- fixed some crashed on derpspace (general is still empty)
- Sync with last derp source
Notes
• Gapps are included
• Fod not working on gtx8_spi devices
• Remebering, Don't report bugs without logs.
Know bugs:
- Screen record
- Fod on gtx8_spi
- sepolicy permissive (not a bug but u know some call it as bug)
By @TeamMEX_XDA
Donate PayPal