21_indexes_recursive_splitter.py 978 B

1234567891011121314151617181920212223242526272829303132333435
  1. from pathlib import Path
  2. import sys
  3. sys.path.append(str(Path(__file__).resolve().parents[1]))
  4. from _chapter2_config import print_dependency_hint
  5. try:
  6. from langchain_text_splitters import RecursiveCharacterTextSplitter
  7. except ModuleNotFoundError as exc:
  8. print_dependency_hint(exc)
  9. raise SystemExit(1)
  10. def main() -> None:
  11. text_splitter = RecursiveCharacterTextSplitter(
  12. chunk_size=20,
  13. chunk_overlap=6,
  14. length_function=len,
  15. separators=["\n\n", "\n", " ", ""],
  16. )
  17. text = """
  18. 人工智能正在快速发展,尤其是大语言模型的应用,正在改变人类的工作方式。
  19. 它们可以帮助人们进行写作、代码生成、甚至是科研探索。
  20. 相比之下,新能源的发展同样重要。
  21. 电动车和太阳能正在逐渐替代传统能源,减少碳排放,对全球环境保护至关重要。
  22. """
  23. docs = text_splitter.split_text(text)
  24. print(docs)
  25. if __name__ == "__main__":
  26. main()