Как изменить подход, чтобы извлекать email из файла размером 10 ГБ при лимите памяти контейнера 256 МБ?
Asked at
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 / Сбер
- app = FastAPI() def get_db(): db = SessionLocal() try: yield db finally: db.close() def heavy_text_parser(file_id: int, db: Session): # Parsing a file that takes 5 minutes parse_and_save(file_id, db) @app.post("/upload") async def upload_file( background_tasks: BackgroundTasks, db: Session = Depends(get_db) ): file_id = save_file_to_db(db) db.commit() background_tasks.add_task(heavy_text_parser, file_id, db) return {"status": "parsing started"}
- def extract_emails_from_huge_file(file_path: str) -> list[str]: with open(file_path, 'r', encoding='utf-8') as f: content = f.read() # Заменяем переносы строк, чтобы текст был "сплошным" content = content.replace('\r\n', ' ').replace('\n', ' ') lines = content.split(' ') emails = [word for word in lines if '@' in word] return emails
Similar questions
- With a large offset, all the preceding records have to be read. What alternative approaches can solve this offset problem?
- Consider this scenario: an application written in Python is leaking memory. A profiler shows that a very large number of small objects are being created, and the garbage collector can't keep up with cleaning them up. What temporary solution would you suggest to stop the memory leak right now?
- Are you satisfied with the proposed further process: send CV and answers by email, then book a short call for preparation?
- How can access be restricted or denied to users registered with email addresses in the yahoo.com domain?
- How to make data collection idempotent if 10 identical requests arrive simultaneously?