如何实现文本按多标点分句并保留原标点?代码优化问询
Got it, let's fix this up for you! Your current code only splits on . and ends up replacing all sentence endings with periods, which isn't what you want. Plus it can't handle cases where a sentence ends without a space before the next one (like today.Are in your example).
Here's a better approach using Python's regex module to correctly identify and preserve all three punctuation marks, while cleaning up spacing issues:
import re # Assume your input text is stored in this variable (replace with your file reading logic) text = "I have a friend. I have many friends! I am very happy today.Are you happy? I wish you were." # Use regex to extract all sentences ending with ., ?, or ! # The pattern matches: optional leading spaces + sentence content + ending punctuation sentences = re.findall(r'\s*[^.!?]+[.!?]', text) # Clean up each sentence by removing extra leading/trailing whitespace processed_sentences = [sent.strip() for sent in sentences] # Option 1: Write sentences joined with spaces (matches your example output) with open("file.txt", 'w') as writefile: writefile.write(' '.join(processed_sentences) + '\n') # Option 2: Write each sentence on a new line (like your original code intended) # with open("file.txt", 'w') as writefile: # for sent in processed_sentences: # writefile.write(sent + '\n')
How This Works:
- Regex Pattern Breakdown:
r'\s*[^.!?]+[.!?]'\s*: Matches any number of leading spaces (handles inconsistent spacing after punctuation)[^.!?]+: Matches one or more characters that aren't.,?, or!(the main content of the sentence)[.!?]: Matches the ending punctuation mark we want to preserve
re.findall(): Extracts all full sentences (with their original punctuation) from the textstrip(): Removes extra spaces from the start/end of each sentence so we don't get messy spacing in the output
Why Your Original Code Failed:
text.split('.')only splits on periods, so it ignores!and?entirely- It discards the original punctuation and adds a period to every split segment, which breaks sentences that should end with
!or? - It can't fix cases where punctuation is followed directly by the next sentence (like
today.Are)
Testing this with your example input will produce exactly the output you want:
Input: "I have a friend. I have many friends! I am very happy today.Are you happy? I wish you were."
Output: "I have a friend. I have many friends! I am very happy today. Are you happy? I wish you were."
内容的提问来源于stack exchange,提问作者Subha Maharjan

