- Author:
- SmileyChris
- Posted:
- May 21, 2009
- Language:
- Python
- Version:
- 1.0
- Score:
- 6 (after 8 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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
There is a small typo:
h(ier...
->h(eir...
#
Please login first before commenting.