Skip to content
Advertisement

Seach txt File for a keyword like [word & random number]

I have this code:

with open("Text.txt") as txtFile:
    for num, line in enumerate(txtFile, 1):
        if "ABC" in line:
            keyWord = "ABC"
            keyWord = "#" + keyWord + "#"

I want to search Text.txt for a keyword that contains a random number, that looks like this:

Keyword = [Word & random Number] or [ABC-1] / [ABC-1234]

The “Word” part is always the same but the number is up to 4 decimals (1-9999).

When the keyword is found, i want to highlight it like this:

ABC-1 to #ABC-1# with

keyWord = "ABC-1"

keyWord = "#" + keyWord + "#"

Question:

How can i search the file for ABC-1 and not just ABC

Advertisement

Answer

Using regular expressions and backreferences

import re

with open("text.txt", 'r') as txt_file:
    with open("new_text.txt", 'w') as new_file:
        p = re.compile('(ABC-d{1,4})')
        for line in txt_file:
            new_line = p.sub(r'#1#', line)
            new_file.write(new_line)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement