-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #27 from MadBomber/split-on-sentences
split-on-sentences
- Loading branch information
Showing
3 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
# frozen_string_literal: true | ||
|
||
module Baran | ||
class SentenceTextSplitter < TextSplitter | ||
def initialize(chunk_size: 1024, chunk_overlap: 64) | ||
super(chunk_size: chunk_size, chunk_overlap: chunk_overlap) | ||
end | ||
|
||
def splitted(text) | ||
# Use a regex to split text based on the specified sentence-ending characters followed by whitespace | ||
text.scan(/[^.!?]+[.!?]+(?:\s+)/).map(&:strip) | ||
end | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
require 'minitest/unit' | ||
require 'baran' | ||
|
||
MiniTest::Unit.autorun | ||
|
||
class TestSentenceTextSplitter < MiniTest::Unit::TestCase | ||
def setup | ||
@splitter = Baran::SentenceTextSplitter.new(chunk_size: 10, chunk_overlap: 5) | ||
end | ||
|
||
def test_chunks | ||
story = <<~TEXT | ||
Hack and jill | ||
went up the hill to fetch | ||
a pail of water. Jack fell | ||
down and broke his crown and Jill | ||
came tumbling after. | ||
The pail went flying! Was the water spilled? | ||
No, the water was splashed on Bo Peep. | ||
TEXT | ||
|
||
chunks = @splitter.chunks(story) | ||
|
||
sentences = chunks | ||
.map { |chunk| | ||
chunk[:text] | ||
.gsub(/\s+/, ' ') | ||
.strip | ||
} | ||
|
||
expected = [ | ||
"Hack and jill went up the hill to fetch a pail of water.", | ||
"Jack fell down and broke his crown and Jill came tumbling after.", | ||
"The pail went flying!", | ||
"Was the water spilled?", | ||
"No, the water was splashed on Bo Peep." | ||
] | ||
|
||
assert_equal(sentences, expected) | ||
end | ||
end |