re module:<\/strong><\/p>\nA regular expression is a name given to the re-package.<\/p>\n
In Python, this package is used to manipulate strings. Moreover, it can be used to determine whether we are searching for a specific search pattern in a string. In other words, suppose we need to identify the occurrence of “p” in “pythonprograms”, we can utilize the re-package for such searches.<\/p>\n
Program to Pluralize a Given Word in Python<\/h2>\n
Approach:<\/strong><\/p>\n\n- Import regex(re) module using the import keyword<\/li>\n
- Create a function say pluralize_word which accepts a word(noun) as an argument and returns the pluralized word<\/li>\n
- Check if the given word matches with the rules using the search() function in the regex module and if the conditional statement<\/li>\n
- If it is true then substitute ‘es’ to the word passed to make it a plural using the sub() function of the regex module<\/li>\n
- If it is true then substitute ‘es’ to the end of the word passed.<\/li>\n
- If it is true then substitute ‘ies’ with ‘y’ to the word passed to make it a plural using the sub() function of the regex module<\/li>\n
- Else just add ‘s’ to the word passed.<\/li>\n
- Give the list as static input and store it in a variable.<\/li>\n
- Iterate in the list of words using the For loop<\/li>\n
- pass the iterator word as an argument to the pluralize_word function(It returns the pluralized word) and print it<\/li>\n
- The Exit of the Program.<\/li>\n<\/ul>\n
Below is the implementation:<\/strong><\/p>\n# Import regex(re) module using the import keyword\r\nimport re\r\n# Create a function say pluralize_word which accepts a word(noun) as an argument and returns the pluralized word \r\ndef pluralize_word(word):\r\n # Check if the given word matches with the rules using the search() function in regex module and if conditional statement \r\n if re.search('[sxz]$', word):\r\n # If it is true then substitute 'es' to the word passed to make it a plural using sub() function of regex module\r\n return re.sub('$', 'es', word)\r\n elif re.search('[^aeioudgkprt]h$', word):\r\n # If it is true then substitue 'es' to the end of the word passed.\r\n return re.sub('$', 'es', word)\r\n elif re.search('[aeiou]y$', word):\r\n # If it is true then substitute 'ies' with 'y' to the word passed to make it a plural using sub() function of regex module\r\n return re.sub('y$', 'ies', word)\r\n else:\r\n # Else just add 's' to the word passed.\r\n return word + 's'\r\n# Give the list as static input and store it in a variable.\r\ngvn_lst = [\"cat\", \"fox\", \"flower\", \"cap\"]\r\n#Iterate in the list of words using the For loop\r\nfor word in gvn_lst:\r\n #pass the iterator word as an argument to the pluralize_word function(It returns the pluralized word) and print it\r\n print(word, '-->', pluralize_word(word))<\/pre>\nOutput:<\/strong><\/p>\n