gpt4 book ai didi

ruby - 正则表达式搜索一个非常大的文件

转载 作者:数据小太阳 更新时间:2023-10-29 07:15:21 26 4
gpt4 key购买 nike

我需要使用正则表达式扫描一个 300MB 的文本文件。

  • 读取整个文件并将其放入变量会占用超过 700MB 的 RAM,然后失败并出现“无法分配内存”错误。
  • 匹配可以在两行或三行中,所以我不能在循环中使用逐行步进。

是否有任何懒惰的方法可以使用正则表达式进行完整文件扫描而不将其读入单独的变量?

UPD

完成。现在您可以使用此功能按 block 读取。为您的目标修改它。

def prepare_session_hash(fname, regex_string, start=0)
@session_login_hash = {}
File.open(fname, 'rb') { |f|
fsize = f.size
bsize = fsize / 8
if start > 0
f.seek(start)
end

overlap = 200

while true
if (f.tell() >= overlap) and (f.tell() < fsize)
f.seek(f.tell() - overlap)
end
buffer = f.read(bsize)
if buffer
buffer.scan(s) { |match|
@session_login_hash[match[0]] = match[1]
}
else
return @session_login_hash
end
end
}
end

最佳答案

  1. 分块而不是逐行遍历文件,其中 block 是由频繁出现的字符或模式(例如“X”)的出现创建的。
  2. “X”永远不会出现在您的正则表达式中,即“X”是您的正则表达式永远不会匹配字符串的地方。
  3. 在当前 block 中匹配您的正则表达式,提取匹配项并继续下一个 block 。

例子:

This is string with multline numbers -2000
2223434
34356666
444564646
. These numbers can occur at 34345
567567 places, and on 67
87878 pages . The problem is to find a good
way to extract these more than 100
0 regexes without memory hogging.

在本文中,假设所需的模式是数字字符串,例如 /d+/s 匹配多行数字,然后,您可以选择一个 block 创建模式,而不是处理和加载整个文件,在这种情况下说句号 并且只读取和处理直到这个模式,然后移动到下一个 block 。

block #1:

This is string with multline numbers -2000
2223434
34356666
444564646
.

block #2:

These numbers can occur at 34345
567567 places, and on 67
87878 pages

等等。

编辑:也从评论中添加@Ranty 的建议:

Or simply read by some amount of lines, say 20. When you find the match within, clear up to the match end and append another 20 lines. No need for figuring frequently occurring 'X'.

关于ruby - 正则表达式搜索一个非常大的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13910199/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com