What's the best way to replace articles in a string?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By xicus

Say I have format strings like

"This is a %s"

and the placeholder could be anything, like “axe” or “bottle”.
What’s the best way to use the correct article (an axe, a bottle)?

:bust_in_silhouette: Reply From: Eric Ellingson

Unless you want to write a library to handle all the different exceptions, i think you might be best creating a autoloaded or static class where you can register each word that you’ll possibly use in dictionary.

Grammar.gd (autoloaded)

extends Node

const articles = {
    'axe': 'an',
    'bottle': 'a',
}

func withArticle(word : String) -> String:
    if not articles.has(word.to_lower()):
        print_debug("Word [%s] does not have a registered article" % word)
        return "a " + word
    return articles[word.to_lower()] + " " + word

Then you can later use it like:

"This is %s %s" % [Grammar.articles[word], word]
# or
"This is %s" % Grammar.withArticle(word)

however, if you wanted to be more flexible, you could try to port something to gdscript from the examples given here: php - Programmatically determine whether to describe an object with "a" or "an"? - Stack Overflow

Eric Ellingson | 2019-07-29 20:38