gpt4 book ai didi

Ruby 扫描以匹配多个单词

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

<分区>

我有一段代码可以解析文件夹中的文本文件,并在特定搜索词周围保存文本。

但是,我在编辑代码以使其同时适用于多个单词时遇到了问题。我不想循环整个代码,因为我希望结果针对每个文本文件进行分组,而不是针对每个搜索词进行分组。

使用 all_documents.scan("(word1|word2|word3)") 或类似的正则表达式变体似乎不起作用。

    #helper
def indices text, index, word
padding = 20
bottom_i = index - padding < 0 ? 0 : index - padding
top_i = index + word.length + padding > text.length ? text.length : index + word.length + padding
return bottom_i, top_i
end

#script
base_text = File.open("base.txt", 'w')
Dir::mkdir("summaries") unless File.exists?("summaries")
Dir.chdir("summaries")

Dir.glob("*.txt").each do |textfile|
whole_file = File.open(textfile, 'r').read
puts "Currently summarizing " + textfile + "..."
curr_i = 0
str = nil
whole_file.scan(/trail/).each do |match|
if i_match = whole_file.index(match, curr_i)
top_bottom = indices(whole_file, i_match, match)
base_text.puts(whole_file[top_bottom[0]..top_bottom[1]] + " : " + File.path(textfile))
curr_i += i_match
end
end
puts "Done summarizing " + textfile + "."
end
base_text.close

有什么想法吗?

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