Python bestimmtes Wort suchen und markieren

Gast #4593773
Lesenswert?

Falls du die Position wissen willst:

1
txt_info = "Ich bin ein Text und ich möchte, dass das Wort lila gefunden wird."
2

3
print(txt_info.find("lila"))
4
# oder
5
print(txt_info.index("lila"))

Bei index wird eine Exception geworfen, wenn nichts gefunden wurde. find 
gibt in diesem Fall -1 zurück und es gibt keine Exception.
Gast #4593804
Lesenswert?

1
# -*- coding: utf-8 -*-
2

3
import re
4

5
txt_info = u"ich bin ein Text und ich möchte das das Wort lila gefunden wird"
6
to_find = 'lila'
7

8
print(
9
    re.sub(
10
        "({})".format(re.escape(to_find)),
11
        r"\033[31;40m\g<0>\033[0m",
12
        txt_info)
13
)

https://docs.python.org/3/library/re.html#re.sub
https://docs.python.org/3/library/stdtypes.html#str.format
https://en.wikipedia.org/wiki/ANSI_escape_code bzw. 
http://ascii-table.com/ansi-escape-sequences.php

unter windows wird es wahrscheinlich nicht funkionieren, da bietet sich 
eine library wie https://pypi.python.org/pypi/colorama an, dann klappt 
das mit der regular expression allerdings nicht mehr.

Antwort schreiben

Bitte melde dich an, um einen Beitrag zu schreiben.

oder

Mit Google-Account einloggen

Die Registrierung ist kostenlos und dauert nur eine Minute.

Jetzt registrieren