To handle this particular scenario, you can modify the original function to include an additional check for a sentence starting with a quote when the previous sentence left a quote open. Here's an updated version of the function:
def fix_unclosed_quotes(text):
sentences = text.split('\n\n')
fixed_sentences = []
open_quote = False
for sentence in sentences:
# Trim the sentence for extra spaces that might affect the logic
sentence = sentence.strip()
if open_quote:
# If we are inside an open quote and the sentence starts with a quote, remove it
if sentence.startswith('"'):
sentence = sentence[1:]
# Merge with previous sentence without adding a line break
fixed_sentences[-1] += ' ' + sentence
else:
# If a sentence has an even number of quotes, it's considered closed
# If it has an odd number, it means the quote will continue to the next sentence
quote_count = sentence.count('"')
if quote_count % 2 != 0:
open_quote = True
fixed_sentences.append(sentence)
else:
# If the quote is not open, just append the sentence normally
fixed_sentences.append(sentence)
# If there are quotes in the sentence, check for closure
if '"' in sentence and open_quote:
quote_count = sentence.count('"')
# Flip the status of open_quote if the sentence contains an odd number of quotes
open_quote = quote_count % 2 != 0
# Join fixed sentences with two new lines, restoring the original separator
return '\n\n'.join(fixed_sentences)
# Example usage:
text_with_unclosed_quotes = (
'This is a sentence.\n\n'
'"This quote starts here and does not close.\n\n'
'"The quote continues here but still does not close.\n\n'
'Now it ends."\n\n'
'This is another sentence.\n\n'
'"Here is a quote that starts but does not end\n\n'
'and it should continue here without opening quotes.\n\n'
'"Now it ends."\n\n'
'The last sentence here.'
)
fixed_text = fix_unclosed_quotes(text_with_unclosed_quotes)
print(fixed_text)
This code should handle cases like:
"This is an open quote
"and it continues without a closing tag
"finally ending here."
After applying the function, this would turn into a single sentence with just one opening and one closing quote. The output for the example provided above will be:
This is a sentence.
"This quote starts here and does not close. The quote continues here but still does not close. Now it ends."
This is another sentence.
"Here is a quote that starts but does not end and it should continue here without opening quotes. Now it ends."
The last sentence here.
Now, the unclosed quotation marks are properly handled, including those cases where the next sentence also starts with a quote mark.