使用python从10 GB的单行日志文件中筛选所有IP地址
最近在分析日志时遇到了一个问题 “需要读取10GB大小的单行日志文件,并且必须打印所有IP地址” 问题:无法逐行读取以避免内存损坏。我必须一个字一个字地写 解决方案:使用python从10 GB的单行日志文件中筛选所有IP地址,python,file,Python,File,最近在分析日志时遇到了一个问题 “需要读取10GB大小的单行日志文件,并且必须打印所有IP地址” 问题:无法逐行读取以避免内存损坏。我必须一个字一个字地写 解决方案: #!/usr/bin/python import re def getIP(): ip = re.compile('\d+|\\.') out = [] with open("./ipaddr","r") as f: while True:
#!/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()])
任何简化的想法都可以做到这一点:
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:]
文件格式是什么?不能用某种形式的正则表达式来解决这个问题吗?这些IP地址是如何格式化的?它们是IPv4吗?IPv6?这似乎不是一个经过深思熟虑的要求。不管设计是什么——或者说缺少设计。为什么不能使用
readline
?换行符将结束您案例中的ip地址。您的解决方案将返回任何数字和点的集合,事件4546
或9999999999.99999