我有一个代码解析文件夹中的文本文件,并将文本保存在某个搜索词的周围。Ruby扫描以匹配多个词
但是,我无法编辑代码,因此它可以同时处理多个单词。我不想循环整个代码,因为我想为每个文本文件分组结果,而不是为每个搜索词分组。
使用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
任何想法?
完美。有用。谢谢! – Seeb 2013-03-18 09:26:39