Replace words with better text


I am trying to rely more on the voice than the dash board. My problem is this. The sensor spits out the best route as this: SR-4 BYP S; Springfield Pike Springdale. So I don’t have to watch the sensor all the time and rewrite everytime it changes wording. Is there a way to make it replace SR-4 BYP S (only) with BYPASS 4? Write now I have to create if statements for the whole phrase. If it changes I get nothing. If I can change each word that would be great.

Create a template sensor in the UI under Helpers, with a State Template like this:

{% set ns = namespace(s=states('sensor.YOUR_SENSOR_ID')) %}
{% set rd = {"SR-4 BYP S": "BYPASS 4",
             "Another phrase": "Another replacement",
             "Final phrase": "Final replacement"} %}
{% for r in rd.keys()|select('in',ns.s) %}
{% set ns.s = ns.s|replace(r, rd[r]) %}
{% endfor %}
{{ ns.s }}

Then use that new sensor in place of the old one. Remember sensor states are limited to 255 characters.

Note that the for list is evaluated once at the start of the loop, so you can’t do sequential swaps this way: x to y to z.

Perfection! thanks. I knew there was a better way. I just could not get my head wrapped around it. This will help is a lot other places also. The only things I had to change was

{% set ns = namespace(s=states('sensor.YOUR_SENSOR_ID')) %}

to this

{% set ns = namespace(s=state_attr('sensor.df_electronics', 'route')) %}

Definitely watch out for the length limit if the input is from an effectively-unlimited attribute into a 255-character-maximum state.

You can create template sensors with attributes, but you’ll have to use YAML for that.

Thanks for the information. For that area. I should never come close to 255. May be 25 to 50 characters max.

1 Like