🐍 Простые фишки парсинга в Python
1️⃣ Парсинг больших JSON-файлов без загрузки в память
import ijson
with open("big.json", "r") as f:
for item in ijson.items(f, "records.item"):
print(item) # потоковый парсинг, не держим всё в памяти
2️⃣ HTML-парсинг с поддержкой XPath через lxml
from lxml import html
doc = html.fromstring("Hello")
print(doc.xpath("//span/text()")[0]) # Hello
3️⃣ Парсинг логов с регулярками и именованными группами
import re
line = '2025-08-23 12:10:45 [INFO] User=egor Action=login'
pattern = r'(?P\d{4}-\d{2}-\d{2}) .* User=(?P\w+) Action=(?P\w+)'
m = re.search(pattern, line)
print(m.groupdict())
# {'date': '2025-08-23', 'user': 'egor', 'action': 'login'}
4️⃣ Парсинг YAML c поддержкой типов
import yaml
data = yaml.safe_load("""
user: egor
active: true
age: 30
""")
print(data) # {'user': 'egor', 'active': True, 'age': 30}
5️⃣ Парсинг бинарных данных (struct)
import struct
raw = b"\x01\x00\x00\x00\x2A\x00"
id, value = struct.unpack("
@Python_Community_ru
Post #2813
865