Login

"an" filter

Author:
SmileyChris
Posted:
May 21, 2009
Language:
Python
Version:
1.0
Tags:
template-filter grammar
Score:
5 (after 7 ratings)

A template filter which returns "a" or "an" depending on the phonetic value of given text.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import re
from django import template
from django.utils.encoding import force_unicode
from django.template.defaultfilters import stringfilter

CONSONANT_SOUND = re.compile(r'''
one(![ir])
''', re.IGNORECASE|re.VERBOSE)
VOWEL_SOUND = re.compile(r'''
[aeio]|
u([aeiou]|[^n][^aeiou]|ni[^dmnl]|nil[^l])|
h(ier|onest|onou?r|ors\b|our(!i))|
[fhlmnrsx]\b
''', re.IGNORECASE|re.VERBOSE)
register = template.Library()

@register.filter
@stringfilter
def an(text):
    """
    Guess "a" vs "an" based on the phonetic value of the text.

    "An" is used for the following words / derivatives with an unsounded "h":
    heir, honest, hono[u]r, hors (d'oeuvre), hour

    "An" is used for single consonant letters which start with a vowel sound.

    "A" is used for appropriate words starting with "one".

    An attempt is made to guess whether "u" makes the same sound as "y" in
    "you".
    """
    text = force_unicode(text)
    if not CONSONANT_SOUND.match(text) and VOWEL_SOUND.match(text):
        return 'an'
    return 'a'

More like this

  1. E-mail quoting filters and tags by ChipX86 7 years, 9 months ago
  2. Type checking templatetag filters by marcorogers 5 years, 1 month ago
  3. Filter for adding quote marks by olau 7 years, 4 months ago
  4. "If in" template tag by andrew 6 years, 11 months ago
  5. Generate Javascript-Safe string in template by SpikeekipS 8 years, 1 month ago

Comments

Please login first before commenting.