Home > Software design >  Converting plural words to singular in Python
Converting plural words to singular in Python

Time:07-28

I have an Excel file with word count as below:

1.Chip, 5
2.Chips,8
3.Car, 2
4.Cars, 6

I want to make output as:

Chip 13
Car 8

CodePudding user response:

You can use the inflect package with a defaultdict like this:

from collections import defaultdict
import inflect

p = inflect.engine()
l = {"chip": 5, "chips": 8, "car": 2, "cars": 6}
updated = defaultdict(int)
for k, v in l.items():
    singular_key = p.singular_noun(k) or k  # make singular if needed
    updated[singular_key]  = v

print(dict(updated))

Which gives the output:

{'chip': 13, 'car': 8}

CodePudding user response:

consider using this package to singularize str values: https://pypi.org/project/inflection/

It's not perfect, but it's a quick way to get something better than trying to come up with some ad-hoc function.

To be more accurate, you could query an actual dictionary, e.g. use https://pypi.org/project/requests/ to query https://www.thefreedictionary.com/ for the singular form of any particular word.

  • Related