我有一个代码可以解析文件夹中的文本文件,并在某个搜索词周围保存文本.
但是,我在编辑代码时遇到问题,因此它可以同时处理多个单词.我不想循环整个代码,因为我希望为每个文本文件分组结果,而不是为每个搜索词分组.
使用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
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
toc*_*och 10
你可以用Regexp.union()它.它完全符合你的要求.
在你的代码中,它将成为
...
whole_file.scan(Regexp.union(/trail/, /word1/, /word2/, /word3/)).each do |match|
...
Run Code Online (Sandbox Code Playgroud)