Home > Net >  How do I make a program recognize whether to use A or An based on the variable the user inputs?
How do I make a program recognize whether to use A or An based on the variable the user inputs?

Time:01-06

This is my second day using Python. I'm using Visual Studios Code with Python 3. I'm trying to make a madlib program in python. I'm having trouble with figuring out how to have the program automatically recognize whether to use a or an based on the variable they entered when I asked. For now I just have a(n) to be safe but I don't know how to just have it recognize that if they input the word apple then the program should say "an apple" or if they put grape then it should say "a grape"

print(timemin, "minutes later.",capitalize_string, "used a(n)", noun1, "to luer it outside.")
print("Suddenly, a(n)", animal2, "raced towards us and caused ")

capitalize_string, animal2, timein, noun1 are all variables.

I tried googling my problem but have not been able to find any help. I just want to learn how to make my program automatically recognize if the variable needs an (a or an) so that when the madlib prints out, it doesn't say "Jeff saw a(n) apple" but instead says "Jeff saw an apple" because the program recognized the variable started with a vowel.

CodePudding user response:

I just convert the name to all lowercase, then check if the first letter is a vowel and doesen't start with "eu", "ur", "uni". There is also an exeption when the word starts with an unaspirated H, but it is extremely rare in English. The four words "hour", "honest", "honor", "herb" and their variations "honestly", "honorable", "herbalist", etc. represent all the words in English that use an unaspirated H.

def get_article(word):
    # Source for the rules: https://www.lawlessenglish.com/learn-english/grammar/indefinite-article/
    VOWELS = "aeiou"
    EXEMPTIONS = ("hour", "honest", "honor", "herb")
    l_word = word.lower()
    if (l_word[0] in VOWELS and not l_word.startswith(("eu", "ur", "uni"))) or l_word.startswith(EXEMPTIONS):
        return "an"
    return "a"

# Example usage:
animal = input("Please enter an animal name: ")
print(f"Suddenly, {get_article(animal)} {animal} raced towards us and caused...")

CodePudding user response:

"An umbrella", but "a user". Unfortunately, English uses the first sound, not the first letter, to determine whether to use "an" or "a".

In some dialects, you even distinguish between "a history" but "an historian" because accented "h" is treated differently than an unaccented one.

If you check to see if the lower-cased first letter is an "a", "e", "i", "o", or "u", you'll probably get about 95% accuracy. Beyond that is a lot of hard work.

  • Related