简体   繁体   中英

How to handle grammar in python-docx

I'm a novice programmer and I suspect this code is terrible. Can someone offer suggestions or code this in a better way? I'm trying to generate text in python-docx and need to handle grammar. This is what I've come up with:

PartiesCount = {1: ''}
InversePlural = {1: 's'}
PossessivePlural = {1:'’s'}
IsAre = {1:'is'}
def ps(PCount):
    return PartiesCount.get(PCount, 's')
def ds(DCount):
    return PartiesCount.get(DCount, 's')
def pso(PCount):
    return InversePlural.get(PCount, '')
def dso(DCount):
    return InversePlural.get(DCount, '')
def ppp(PCount):
    return PossessivePlural.get(PCount, "s’")
def dpp(DCount):
    return PossessivePlural.get(DCount, "s’")
def pisare(PCount):
    return IsAre.get(PCount, 'are')
def disare(DCount):
    return IsAre.get(DCount, 'are')

In: 'The cat' + ps(PCount) + ' ' + pisare(PCount) + ' neat.'

If PCount > 1: The cats are neat.

If PCount = 1: The cat is neat.

There's gotta be a better way to accomplish this than what I'm doing. At a minimum, a better way to code this. Any suggestions? Thanks

It looks like you're trying to handle grammar rules for singular and plural nouns and verbs in your code. A way to simplify this code and make it more maintainable would be to use a library like inflect , which provides an easy way to handle singular/plural forms of words in English.

import inflect

p = inflect.engine()

In: 'The ' + p.plural_noun('cat', PCount) + ' ' + p.plural_verb('is', PCount) + ' neat.'

If PCount > 1: The cats are neat.

If PCount = 1: The cat is neat.

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM