폴더의 텍스트 파일을 구문 분석하고 특정 검색 단어 주위에 텍스트를 저장하는 코드가 있습니다.여러 단어와 일치하는 루비 스캔
그러나 동시에 여러 단어에 대해 작동하도록 코드를 편집하는 데 문제가 있습니다. 결과를 모든 텍스트에 그룹화하지 않고 모든 텍스트 파일에 그룹화하려는 경우 전체 코드를 반복하지 않으려 고합니다.
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