如何使用RegEx按指定规则将长字符串拆分为多个段落?
How to Split a Long String into Paragraphs After the First Period Beyond 250 Characters
Approach
The core idea is to iteratively find the appropriate split points without breaking mid-sentence:
- Start from the beginning of the string.
- For each iteration, check if we’ve reached the end of the string. If not, jump to the 250th character from the current position.
- Look for the first period (
.) starting from that position—this ensures we split after a complete sentence. - Split the string at that period, add a newline, and continue processing the remaining part of the string.
Python Implementation
Here’s a practical function that implements this logic, with optional customization for the character limit:
def split_into_paragraphs(original_string, char_limit=250): result = [] current_pos = 0 str_length = len(original_string) while current_pos < str_length: # If remaining characters are under the limit, add the rest and exit if str_length - current_pos <= char_limit: result.append(original_string[current_pos:]) break # Find the first '.' after the char_limit from current position search_start = current_pos + char_limit period_index = original_string.find('.', search_start) # Fallback: if no period found (edge case), split at the char limit if period_index == -1: period_index = current_pos + char_limit # Add the complete sentence block and move to next position result.append(original_string[current_pos:period_index + 1]) current_pos = period_index + 1 # Join all blocks with newlines to form paragraphs return '\n'.join(result) # Example usage with your original string originalString = 'Lorem ipsum dolor sit amet, eu ius everti consequat instructior, sed modus vitae nostrud cu, ad. principes iracundia efficiendi pro. Et eam movet iudico ancillae. Ei mucius invidunt assueverit sit, nostrum oportere ne ius, qui similique scripserit heus et. Eam an tota mollis placerat, an quem voluptua appellantur est.Stet movet quaerendum his ea. Eum facete consequuntur ea, in vix liber quodsi. Percipit moderatius his et, id viderer salutandi vix. Scaevola suscipiantur id quo, ne eirmod consetetur cotidieque sit. Habemus noluisse ex ius.Cum ut dicant everti. Per ad vero exerci. Dolor eruditi eu eos. Alii fugit iisque sea ei, ponderum theophrastus concludaturque nec in. Eam ea modo dolores, has case pericula forensibus id.Laudem appetere senserit qui eu, pro ut essent euripidis. Vim ut elit utinam ridens, his facilis placerat eu. Mel omnis causae eripuit ei, mel no cibo essent temporibus, an quot efficiantur mea. Cu duo diam errem accommodare, nisl posse equidem an vis, his no omnes partem.' finalString = split_into_paragraphs(originalString) print(finalString)
Explanation
- Initialization: We start with an empty list to collect each paragraph block and set
current_posto the start of the string. - Loop Through Content: For each pass, we check if the remaining text is shorter than char_limit—if so, we add it to the result and wrap up.
- Locate Split Point: Using
str.find(), we pinpoint the first period after the 250-character mark to avoid splitting in the middle of a sentence. - Build Paragraphs: We append each complete sentence block to the result list, then update our position to start processing after the last period.
- Finalize: We join all blocks with newlines to create the properly formatted paragraph-separated string.
Edge Case Handling
If no period is found after the 250-character mark (a rare scenario given your input structure), the function falls back to splitting exactly at the character limit to prevent infinite loops. You can adjust this fallback behavior if needed for your specific use case.
内容的提问来源于stack exchange,提问作者john sadeghi
相关产品推荐
相关产品推荐

