Python中如何移除字符串的前3个指定结尾的句子
用Python移除字符串前3个指定规则句子的实现方法
需求说明
需要移除news变量字符串中前3个句子,句子判定规则为:以英文句号.、冒号:或连字符-结尾的内容即为一个句子。
实现思路
- 遍历目标字符串,依次定位符合规则的句子结束标记(
./:/-); - 累计找到3个结束标记后,截取该标记之后的剩余内容;
- 处理标记后可能存在的多余空格,保证结果整洁。
代码实现
news = "Waukesha trial: US man sentenced to life for car-ramming attack - BBC NewsBBC HomepageSkip to contentAccessibility HelpYour accountHomeNewsSportReelWorklifeTravelFutureMore menuMore menuSearch BBCHomeNewsSportReelWorklifeTravelFutureCultureMusicTVWeatherSoundsClose menuBBC NewsMenuHomeWar in ArtsHealthWorld News TVIn PicturesReality CheckNewsbeatLong ReadsUS CanadaUS Elections 2022ResultsWaukesha trial: US man sentenced to life for car-ramming attackPublished11 hours agoSharecloseShare pageCopy linkAbout sharingThis video can not be playedTo play this video you need to enable JavaScript in your browser Media caption, Watch: Emotional testimony from victims familiesA Wisconsin judge has sentenced a man who killed six people and injured 62 by driving through a Christmas parade last year to life in prison A jury convicted Darrell Brooks last month after prosecutors argued he had shown \"utter disregard for human life\" The court also heard emotional testimony from dozens of survivors and families of victims during sentencing Brooks represented himself in the four-week trial, often interrupting court proceedings In her sentencing on Wednesday, Judge Jennifer Dorow said Brooks had chosen path of evil" def remove_first_three_sentences(text): separators = {'.', ':', '-'} count = 0 end_pos = 0 for idx, char in enumerate(text): if char in separators: count += 1 end_pos = idx if count == 3: break # 处理找到3个标记后的截取,跳过开头多余空格 result = text[end_pos+1:].lstrip() # 容错:不足3个符合规则的句子则返回原文本 return result if count >=3 else text processed_news = remove_first_three_sentences(news) print(processed_news)
代码说明
separators集合定义了句子的结束判定标记;- 遍历字符串时,每遇到一个结束标记就计数,找到第3个时记录其位置并终止遍历;
- 从第3个标记的下一位开始截取内容,用
lstrip()移除开头的多余空格; - 增加容错逻辑:如果字符串中不足3个符合规则的句子,直接返回原文本。
内容的提问来源于stack exchange,提问作者user20477090
相关产品推荐
相关产品推荐

