[Python] how to extract words following a list of keywords in python using regex?

Discussão em 'Python' iniciado por Stack, Março 14, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to extract locations using Regex in python. Right now I am doing this:

    def get_location(s):
    s = s.strip(STRIP_CHARS)
    keywords = "at|outside|near"
    location_pattern = "(?P<location>((?P<place>{keywords}\s[A-Za-z]+)))".format(keywords = keywords)
    location_regex = re.compile(location_pattern, re.IGNORECASE | re.MULTILINE | re.UNICODE | re.DOTALL | re.VERBOSE)

    for match in location_regex.finditer(s):
    match_str = match.group(0)
    indices = match.span(0)
    print ("Match", match)
    match_str = match.group(0)
    indices = match.span(0)
    print (match_str)

    get_location("Im at building 3")


    I have three issues:

    1. It is only giving "at" as output but it should also give building.
    2. captures = match.capturesdict() I am not able to use to extract captures where this is working other examples.
    3. When I am doing just this location_pattern = 'at|outside\s\w+. It seems to be working. Can someone explains what I am doing wrong?

    Continue reading...

Compartilhe esta Página