Chunking
Example Python Code Samples
1. Naive (Fixed-Size) Chunking
def fixed_size_chunk(text: str, chunk_size: int = 100) -> list[str]:
"""Splits text into fixed-size chunks based on character count."""
chunks = []
for i in range(0, len(text), chunk_size):
chunks.append(text[i : i + chunk_size])
return chunks
# Example:
# text = "This is a sample text to demonstrate fixed-size chunking."
# chunks = fixed_size_chunk(text, 20)
# print(chunks)
# Output: ['This is a sample tex', 't to demonstrate fix', 'ed-size chunking.']function fixedSizeChunk(text: string, chunkSize: number = 100): string[] {
/** Splits text into fixed-size chunks based on character count. */
const chunks: string[] = []
for (let i = 0; i < text.length; i += chunkSize) {
chunks.push(text.slice(i, i + chunkSize))
}
return chunks
}
// Example:
// const text = "This is a sample text to demonstrate fixed-size chunking.";
// const chunks = fixedSizeChunk(text, 20);
// console.log(chunks);
// Output: [ 'This is a sample tex', 't to demonstrate fix', 'ed-size chunking.' ]2. Sentence-Based Chunking
3. Other Chunking
Last updated