You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中同时以换行符(\n)和句号(.)作为分隔符分割文本字符串?

How to split text on both newline (\n) and period (.) in Python

The issue with your current code is that str.split('\n') only splits on newline characters, but you need to also split whenever a period followed by a space (. ) appears. For splitting on multiple delimiters in Python, the re.split() function from the re module is the way to go—it lets you define a regular expression pattern that matches all the delimiters you care about.

Here's how to adjust your code to get the desired output:

import re

text = 'Christmas Perot 2021 TSO\nSkip to Main Content HOME CONCERTS EVENTS ABOUT STAFF EDUCATION SUPPORT US More Use tab to navigate through the menu items. BUY TICKETS SUNDAY, DECEMBER 12, 2021 I PEROT THEATRE I 4:00 PM\nPOPS I Christmas at The Perot\nCLICK HERE to purchase tickets, or contact the Texarkana Symphony Orchestra at 870.773.3401\nA Texarkana Tradition Join the TSO, the Texarkana Jazz Orchestra, and the TSO Chamber Singers, for this holiday concert for the whole family.\nDon’t miss seeing the winner of TSO’s 11th Annual Celebrity Conductor Competition\nBack to Events 2019 Texarkana Symphony Orchestra'

# Split on either ". " (period + space) or "\n" (newline)
sentences = re.split(r'\. |\n', text)
print(sentences)

Output:

['Christmas Perot 2021 TSO', 'Skip to Main Content HOME CONCERTS EVENTS ABOUT STAFF EDUCATION SUPPORT US More Use tab to navigate through the menu items.', 'BUY TICKETS SUNDAY, DECEMBER 12, 2021 I PEROT THEATRE I 4:00 PM', 'POPS I Christmas at The Perot', 'CLICK HERE to purchase tickets, or contact the Texarkana Symphony Orchestra at 870.773.3401', 'A Texarkana Tradition Join the TSO, the Texarkana Jazz Orchestra, and the TSO Chamber Singers, for this holiday concert for the whole family.', 'Don’t miss seeing the winner of TSO’s 11th Annual Celebrity Conductor Competition', 'Back to Events 2019 Texarkana Symphony Orchestra']

Breakdown of the regex pattern:

  • \. : Matches a literal period followed by a space (we escape the period with \ because it has special meaning in regex)
  • |: Acts as an OR operator, so the pattern matches either the first delimiter or the second
  • \n: Matches a newline character

If you ever need to handle edge cases (like periods without a trailing space, or multiple spaces after a period), you can tweak the regex to something like r'\.\s*|\n'—where \s* matches zero or more whitespace characters. But for your specific use case, the original pattern works perfectly.

内容的提问来源于stack exchange,提问作者user17179901

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 20:33:11