フォルダ内のテキストファイルを解析し、特定の検索ワードの周囲にテキストを保存するコードがあります。
ただし、複数の単語に対して同時に機能するようにコードを編集するのに問題があります。検索ワードごとにグループ化するのではなく、テキストファイルごとに結果をグループ化する必要があるため、コード全体をループさせたくありません。
類似した正規表現のバリアントを使用し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
何か案は?