Search code examples
pythonregexpython-3.xregex-lookaroundsregex-group

i want to match Something<alive> (match <alive> and then wanna extract "Something word from it and save it in a list)


!!! a file avengers.txt is attached with code part read that before reading next lines !!!

I wanna match (, , ) and exclude them from (iron man, docter strange, gamora) and save (iron man, docter strange, gamora) on a list

i used r'<(.*alive)>1 to match and same for dusted and died. now i want to sperate iron man from and save it in a list and seperate docter strange from and save it in a seperate list and same for gamora

the code i used to match alive, dusted and died:

#!/usr/bin/env python3

import re

#file = open("avengers.txt", "r")

def alive():
    with open("avengers.txt") as f:
        for i in f:
            rx = re.findall("<(.*alive)>", i)
            print(rx)


def died():
    with open("avengers.txt") as f:
        for i in f:
            rx = re.findall("<(.*died)>", i)
            print(rx)

def dusted():
    with open("avengers.txt") as f:
        for i in f:
            rx = re.findall("<(.*dusted)>", i)
            print(rx)


-----avengers.txt-------
iron man<alive>
doctor strange<dusted>
gamora<died>
------------------------


````````

Solution

  • alive = []
    died = []
    dusted = []
    with open("avengers.txt") as f:
        for i in f:
            i = i.strip()
            if '<alive>' in i:
                alive.append(i.replace('<alive>', ''))
            if '<died>' in i:
                died.append(i.replace('<died>', ''))
            if '<dusted>' in i:
                dusted.append(i.replace('<dusted>', ''))
    
    print('****alive****')
    print(str(alive))
    print('****died****')
    print(str(died))
    print('****dusted****')
    print(str(dusted))
    
    

    avengers.txt

    iron man<alive>
    iron man_2<alive>
    doctor strange<dusted>
    doctor strange_2<dusted>
    gamora<died>
    gamora2<died>