123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185 |
- import re
- from typing import List
- import logging
- import argparse
- import sys
- logger = logging.getLogger(__name__)
- class SentenceUtil:
- """中文文本句子拆分工具类
-
- 用于将中文文本按照标点符号拆分成句子列表
- """
-
- def __init__(self):
- # 定义结束符号,包括常见的中文和英文标点
- self.end_symbols = ['。', '!', '?', '!', '?', '\n']
- # 定义引号对
- self.quote_pairs = [("'", "'"), ('"', '"'), ('「', '」'), ('『', '』'), ('(', ')'), ('(', ')')]
-
- @staticmethod
- def split_text(text: str, length: int = None) -> List[str]:
- """将文本拆分成句子列表
-
- Args:
- text: 输入的文本字符串
- length: 可选参数,指定拆分后句子的最大长度
-
- Returns:
- 拆分后的句子列表
- """
- sentences = SentenceUtil()._split(text)
- if length is not None:
- i = 0
- while i < len(sentences):
- if SentenceUtil().get_valid_length(sentences[i]) <= length and i + 1 < len(sentences):
- sentences[i] = sentences[i] + sentences[i+1]
- del sentences[i+1]
- else:
- i += 1
- return sentences
-
- def _split(self, text: str) -> List[str]:
- """内部拆分方法
-
- Args:
- text: 输入的文本字符串
- length: 可选参数,指定拆分后句子的最大长度
-
- Returns:
- 拆分后的句子列表
- """
- if not text or not text.strip():
- return []
-
- try:
- # 通用拆分逻辑
- sentences = []
- current_sentence = ""
-
- # 用于跟踪引号状态的栈
- quote_stack = []
-
- i = 0
- while i < len(text):
- char = text[i]
- current_sentence += char
-
- # 处理引号开始
- for start, end in self.quote_pairs:
- if char == start:
- if not quote_stack or quote_stack[-1][0] != end:
- quote_stack.append((end, i))
- break
-
- # 处理引号闭合
- if quote_stack and char == quote_stack[-1][0] and i > quote_stack[-1][1]:
- quote_stack.pop()
-
- # 处理结束符号,仅在非引号环境中
- if not quote_stack and char in self.end_symbols:
- if current_sentence.strip():
- # 保留句子末尾的换行符
- if char == '\n':
- current_sentence = current_sentence.rstrip('\n')
- sentences.append(current_sentence)
- current_sentence = '\n'
- else:
- sentences.append(current_sentence)
- current_sentence = ""
-
- # 处理空格 - 保留空格在下一个句子的开头
- if i + 1 < len(text) and text[i + 1].isspace() and text[i + 1] != '\n':
- i += 1
- current_sentence = text[i]
-
- i += 1
-
- # 处理循环结束时的剩余内容
- if current_sentence.strip():
- sentences.append(current_sentence)
-
- # 如果没有找到任何句子,返回原文本作为一个句子
- if not sentences:
- return [text]
-
- return sentences
-
- except Exception as e:
- logger.error(f"拆分文本时发生错误: {str(e)}")
- return []
-
- @staticmethod
- def clean_text(text: str) -> str:
- """去除除中英文和数字以外的所有字符
-
- Args:
- text: 输入的文本字符串
-
- Returns:
- 处理后的字符串
- """
- if not text:
- return text
- return re.sub(r'[^\u4e00-\u9fa5a-zA-Z0-9]', '', text)
- @staticmethod
- def get_valid_length(text: str) -> int:
- """计算只包含中英文和数字的有效长度
-
- Args:
- text: 输入的文本字符串
-
- Returns:
- 有效字符的长度
- """
- if not text:
- return 0
- return len(re.sub(r'[^\u4e00-\u9fa5a-zA-Z0-9]', '', text))
- def split_by_regex(self, text: str) -> List[str]:
- """使用正则表达式拆分文本
-
- 这是一个备选方法,使用正则表达式进行拆分
-
- Args:
- text: 输入的文本字符串
-
- Returns:
- 拆分后的句子列表
- """
- if not text or not text.strip():
- return []
-
- try:
- # 使用正则表达式拆分,保留分隔符
- pattern = r'([。!?!?]|\n)'
- parts = re.split(pattern, text)
-
- # 组合分隔符与前面的部分
- sentences = []
- for i in range(0, len(parts), 2):
- if i + 1 < len(parts):
- sentences.append(parts[i] + parts[i+1])
- else:
- # 处理最后一个部分(如果没有对应的分隔符)
- if parts[i].strip():
- sentences.append(parts[i])
-
- return sentences
- except Exception as e:
- logger.error(f"使用正则表达式拆分文本时发生错误: {str(e)}")
- return [text] if text else []
- if __name__ == '__main__':
- input_text = """急性期护理:
- - 每4h评估腹痛程度 3-1 PDF
- 延续护理: 1-2 PDF
- 患者教育: 3-3 PDF
- - 识别复发症状(发热/黄疸)"""
- sentences = SentenceUtil.split_text(input_text,10)
- for sentence in sentences:
- print(sentence)
- print('-----------')
|