使用python从10gb的单行日志文件中筛选所有IP地址

2024-09-26 22:51:48 发布

您现在位置:Python中文网/ 问答频道 /正文

最近在分析日志时遇到了一个问题。你知道吗

“需要读取10GB大小的单行日志文件,并且必须打印所有IP地址”

问题:无法逐行读取以避免内存损坏。必须一个字接一个字。你知道吗

解决方案:

#!/usr/bin/python
import re
def getIP():
        ip = re.compile('\d+|\\.')
        out = []
        with open("./ipaddr","r") as f:
                while True:
                        c = f.read(1)
                        if not c:
                                break
                        if ip.match(c):
                                out.append(c)
                                for i in range(14):
                                        c = f.read(1)
                                        if ip.match(c):
                                                out.append(c)
                                        else:
                                                if out:
                                                        yield "".join(out)
                                                out = []

print str([ipad for ipad in getIP()])

有什么想法可以简化吗??你知道吗


Tags: 文件内存inipreforreadif
1条回答
网友
1楼 · 发布于 2024-09-26 22:51:48

这应该做到:

import re
from functools import partial

def getIP(file_name):
    ip_regex = re.compile("(?:\d{1,3}\.){3}\d{1,3}")
    current = ""
    with open(file_name) as file:
        for c in iter(partial(file.read, 1), ""):
            current += c
            current = current[-15:]
            m = ip_regex.match(current)
            if m:
                yield m.group()
                current = current[m.endpos:]

相关问题 更多 >

    热门问题