Skip to content

Regular expressions in Python

Here’s the revised documentation for the Python script that reverses the order of words in a sentence similar to the line from Le Bourgeois gentilhomme. The inconsistencies, unprofessional style, and translation issues have been corrected:

The Python programming language provides numerous libraries, including one dedicated to regular expressions, which can be helpful for text manipulation, particularly if you are not familiar with utilities like sed or awk.

The following code demonstrates how to reverse the order of words in a sentence, inspired by the famous line from Le Bourgeois gentilhomme:

#!/usr/bin/python
# coding: utf-8
"""
Prompts the user to type in M. Jourdain's line and
displays a variant. This works only with the following line
or with the same number of words entered between quotation marks:
"Belle marquise, your beautiful eyes make me die of love."
"""
# Import the regular expression library.
import re
# Prompt the user to enter the line and store it in a variable.
original_text = input('Enter M. Jourdain\'s line in quotation marks: ')
# Remove the period from the line.
original_text_without_period = original_text.strip('.')
# Convert the string to a list of words.
shuffled_text = re.split(' ', original_text_without_period)
# Initialize a variable containing an empty string.
final_text = ''
# After verifying that the line contains 9 words, display the first
# word of the modified line, with a capital letter.
if len(shuffled_text) == 9:
# A loop adds to the initially empty string the words of
# M. Jourdain's line, except for the first and last, in the desired order.
for i in [7, 5, 6, 0, 1, 2, 3]:
final_text += ' ' + shuffled_text[i].lower()
# Display the final text, followed by a period.
print(shuffled_text[8].capitalize() + final_text + ' ' +
shuffled_text[4].lower() + '.')
else:
print('The line must be exactly nine words long.')