NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Middle91 views

Как изменить подход, чтобы извлекать email из файла размером 10 ГБ при лимите памяти контейнера 256 МБ?

Practice

AI answer

The file must not be loaded in its entirety: it should be read in small chunks, retaining only a tail long enough to find an email address that spans a chunk boundary. Memory usage then depends on the chunk and tail sizes, not the file size. For example:

import re

EMAIL = re.compile(r"[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@"
                   r"[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?"
                   r"(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+")
CHUNK = 1024 * 1024
OVERLAP = 512  # Must be greater than the maximum length of the email being searched for.

def extract_emails(path):
    tail = ""
    with open(path, encoding="utf-8", errors="replace") as f:
        while chunk := f.read(CHUNK):
            data = tail + chunk
            safe_end = max(0, len(data) - OVERLAP)
            for match in EMAIL.finditer(data):
                if match.end() <= safe_end:
                    yield match.group()
            tail = data[safe_end:]

    for match in EMAIL.finditer(tail):
        yield match.group()

It is important to verify that the chosen pattern and the address length limit are consistent with the requirements. If results need to be saved, they should also be written incrementally rather than accumulated in a list. More complex addressing rules require an appropriate validator; the regular expression above is a practical search pattern, not a complete RFC validation.

Also asked at GigaChat / Сбер

Similar questions