如何用Python按指定规则将拆分文本合并为符合要求的段落?
拆分句子合并为合规段落的实现方案
核心思路
别用零散的if-else硬套判断,改用按顺序累积合并句子的方式:每添加一个句子就验证是否满足所有规则,达标就输出该段落,再从剩余句子重新开始累积。这种方式逻辑清晰,能高效生成符合要求的段落。
规则校验工具函数
先把每个规则拆成独立的校验函数,方便维护:
import re from collections import Counter def has_enough_sentences(batch): # 段落包含超过2个原句子(对应行数超过2行) return len(batch) > 2 def meet_letter_ratio(text): # 计算字母字符占比(忽略空格) non_space_chars = [c for c in text if not c.isspace()] if not non_space_chars: return False letter_count = len([c for c in non_space_chars if c.isalpha()]) return (letter_count / len(non_space_chars)) >= 0.5 def has_period(text): # 至少包含一个句号(原句子自带,合并后必然满足,作为兜底校验) return '.' in text def ends_with_period(text): # 以句号结尾 return text.strip().endswith('.') def meet_word_requirements(text): # 提取单词(转小写去重) words = re.findall(r'\b\w+\b', text.lower()) # 满足至少20个单词,且至少15个不同单词 return len(words) >= 20 and len(Counter(words)) >= 15
合并逻辑实现
def merge_to_paragraphs(sentences): paragraphs = [] current_batch = [] for sent in sentences: current_batch.append(sent) current_text = ' '.join(current_batch) # 逐一验证所有规则 if (has_enough_sentences(current_batch) and meet_letter_ratio(current_text) and has_period(current_text) and ends_with_period(current_text) and meet_word_requirements(current_text)): paragraphs.append(current_text) current_batch = [] # 重置批次,处理剩余句子 # 处理最后一批未达标内容:合并到上一段落(按需调整) if current_batch and paragraphs: paragraphs[-1] = ' '.join([paragraphs[-1], ' '.join(current_batch)]) return paragraphs # 你的输入句子列表 input_sentences = [ 'guided by our core values, weve experienced first-hand how our focused actions both big and small can translate into meaningful experiences for our customers, bringing our purpose to feed and foster community to life each day.', 'with the strength of our full system, weve worked together to build a more diverse, equitable and inclusive business, source more food responsibly, adopt more sustainable practices, and implement innovative and credible solutions in our ongoing quest to be a good neighbor in the communities where we live, work and serve.', 'we are proud of the work we do to make a difference and will continue to help uphold this promise in all of the communities in which we operate.', 'showing up for our communities ray kroc used to say, none of us is as good as all of us a phrase that serves as a constant reminder of mcdonalds impact on the world when we leverage thecollective strength of our system.', 'we all felt this sentiment more deeply overthe past two years as we continued tonavigate the covid-19 pandemic andit is equally as prevalent now as we face ongoing headwinds.', 'front of mind is the continuing humanitarian crisis resulting from the war against ukraine.', 'our hearts and minds remain with the ukrainian people and all impacted, as the ongoing war has brought new elements of uncertainty tocommunities around the world.', 'in moments like these, our number one priority remains our people.' ] # 生成合规段落 result = merge_to_paragraphs(input_sentences) for idx, para in enumerate(result, 1): print(f"段落 {idx}:\n{para}\n")
代码说明
- 工具函数把每个规则独立出来,后续修改规则只需调整对应函数;
- 累积合并+实时校验的方式,避免了复杂的嵌套判断逻辑;
- 最后一批未达标内容可按需合并到上一段落,避免遗漏文本。
内容的提问来源于stack exchange,提问作者yannick
相关产品推荐
相关产品推荐

