Program that pluralize a given word in Python
In English grammar, we have an interesting topic called, “singular and plurals”. In this tutorial let us see how they can be implemented in Python.
Python program to convert singular word to plural
As we all know, singular means denoting an object that is single in number or quantity. For example, ” a book” or ” toy”. Plurals mean denoting objects in groups or many in numbers. For example, “toys” or “lamps”.
So, in this tutorial, we will look at how can this concept be implemented in Python.
A singular noun can be converted to plural by adding “s” in the end.
Words ending with ” sh, s, x, z” can be converted to plural by adding “es” in the end.
A singular word ending in a consonant and then y can be converted to plural by dropping the “y” and adding “ies“.
There might be some exceptions to the above-mentioned rules. But we will restrict ourselves to the given rules.
import re def pluralize(noun): if re.search('[sxz]$', noun): return re.sub('$', 'es', noun) elif re.search('[^aeioudgkprt]h$', noun): return re.sub('$', 'es', noun) elif re.search('[aeiou]y$', noun): return re.sub('y$', 'ies', noun) else: return noun + 's' List=["bush", "fox", "toy", "cap"] for i in List: print(i, '-', pluralize(i))
The re-package is called a regular expression.
The package is used for manipulating strings in Python. In addition to, that it can also be used to check if we are searching for a particular search pattern in a string. In other words, if we have to find the occurrence of “ee” in code speedy. For such searches, we can use the re-package.
Here, there are few words in the list and they have been converted to their corresponding plurals.
OUTPUT:
bush - bushes fox - foxes toy - toys cap - caps
Also read: Count the number of capital letters in a string in Python
for ‘toy’, holiday its printing toies, holidaies
#The carrot on the vowel will help solve that
import re
def pluralize(noun):
if re.search(‘[sxz]$’, noun):
return re.sub(‘$’, ‘es’, noun)
elif re.search(‘[^aeioudgkprt]h$’, noun):
return re.sub(‘$’, ‘es’, noun)
elif re.search(‘[^aeiou]y$’, noun):
return re.sub(‘y$’, ‘ies’, noun)
else:
return noun + ‘s’
List=[“baby”, “boy”, “axe”, “box”, “loss”, “moth”, “baby”]
for i in List:
print(i, ‘-‘, pluralize(i))