Convert directions like NE and ESE to words for text to speech


@TOBob posed an interesting question in a private message about converting wind direction abbreviations to words to allow the weather data to be spoken. They had already figured most of it out one way or another but I wanted to share this solution for anyone who might find it useful.

Consider the text “Highs in the low 60s and lows in the low 40s with wind gusts from the WSW.” We want to convert WSW to West South West so that the phrase is compatible with text to speech.

Here is an expression that converts any direction (e.g. N, NW, ESE) to text without affecting other words and phrases:

        '/(\\b[NESW]*)N([NESW]*\\b)/', '$1 North $2',
        '/(\\b[NESW]*)E([NESW]*\\b)/', '$1 East $2',
        '/(\\b[NESW]*)S([NESW]*\\b)/', '$1 South $2',
        '/(\\b[NESW]*)W([NESW]*\\b)/', '$1 West $2',
        '/(\\b)N(\\b)/', ' North ',
        '/(\\b)E(\\b)/', ' East ',
        '/(\\b)S(\\b)/', ' South ',
        '/(\\b)W(\\b)/', ' West '

The last 4 replacements are to catch the secondary intercardinal directions; the first 4 will for example convert “NNW” to “North N West” so that last batch cleans up the wayward N. There are a few tests cases in this example piston to make sure it doesn’t mess with N E W S appearing in other words:

The piston will log the following:

N … ESE … NNW … SSE … SW … N S E W … news Not Sun AWW WoW … NW … S

North … East South East … North North West … South South East … South West … North South East West … news Not Sun AWW WoW … North West … South

That replacement uses regular expressions, so to briefly explain: '/(\\b[NESW]*)W([NESW]*\\b)/'means find a capital W that is either surrounded by word break characters like spaces, commas, etc (\\b), or is part of a word containing only characters N E S W in any order. The forward slashes just tell webCoRE to process the replacement as a regular expression.

I hope this is useful for someone!


Fantastic! I can use this immediately. Thanks!


Indeed, it works brilliantly! Thanks again, Ian.