forked from SylphAI-Inc/AdalFlow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadalflow_text_splitter.py
80 lines (58 loc) · 2.09 KB
/
adalflow_text_splitter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"Code for tutorial: https://adalflow.sylph.ai/tutorials/text_splitter.html"
from adalflow.components.data_process.text_splitter import TextSplitter
from adalflow.core.types import Document
from typing import Optional, Dict
def split_by_words(
text: str, chunk_size: int = 5, chunk_overlap: int = 1, doc_id: Optional[str] = None
) -> list:
text_splitter = TextSplitter(
split_by="word", chunk_size=chunk_size, chunk_overlap=chunk_overlap
)
doc = Document(text=text, id=doc_id or "doc1")
return text_splitter.call(documents=[doc])
def split_by_tokens(
text: str, chunk_size: int = 5, chunk_overlap: int = 0, doc_id: Optional[str] = None
) -> list:
text_splitter = TextSplitter(
split_by="token", chunk_size=chunk_size, chunk_overlap=chunk_overlap
)
doc = Document(text=text, id=doc_id or "doc1")
return text_splitter.call(documents=[doc])
def split_by_custom(
text: str,
split_by: str,
separators: Dict[str, str],
chunk_size: int = 1,
chunk_overlap: int = 0,
doc_id: Optional[str] = None,
) -> list:
text_splitter = TextSplitter(
split_by=split_by,
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
separators=separators,
)
doc = Document(text=text, id=doc_id or "doc1")
return text_splitter.call(documents=[doc])
def example_usage():
text = "Example text. More example text. Even more text to illustrate."
word_splits = split_by_words(text, chunk_size=5, chunk_overlap=1)
print("\nWord Split Example:")
for doc in word_splits:
print(doc)
token_splits = split_by_tokens(text, chunk_size=5, chunk_overlap=0)
print("\nToken Split Example:")
for doc in token_splits:
print(doc)
question_text = "What is your name? How old are you? Where do you live?"
custom_splits = split_by_custom(
text=question_text,
split_by="question",
chunk_size=1,
separators={"question": "?"},
)
print("\nCustom Separator Example:")
for doc in custom_splits:
print(doc)
if __name__ == "__main__":
example_usage()