[Python] Pattern match multiple values in a sentence

Discussão em 'Python' iniciado por Stack, Julho 7, 2025.

  1. Stack

    Stack Membro Participativo

    I have a sentence that has a specific format.

    <subject> <action> <object> @ <price> ... // The sentence can continue


    and I want to extract these values out of the sentence.

    Constraints:

    • The subject is always Bob or Alice
    • Action is either bought or sold
    • The object can be any word of 1-7 letters // 4apples should return NULL
    • Price is either a float/integer
    • There can be sentences before subject but guaranteed to not contain Bob/Alice.
    • There may or may not be a space after @

    Example:

    Hi there, Bob sold apples @2.0 dollars each


    Desired Output:

    Subject: Bob
    Action: sold
    Object: apples
    Price: 2.0


    Currently, I do it the naive way by:

    #!/usr/bin/env python3

    sentence = "Hi there, alice sold apples @2.0 dollars each"

    sentence = sentence.lower()

    if 'alice' in sentence or 'bob' in sentence:

    s_list = sentence.split(" ")
    s_idx = -1

    if 'bob' in sentence:
    s_idx = s_list.index('bob')
    elif 'alice' in sentence:
    s_idx = s_list.index('alice')

    if s_idx > -1:
    Subject = s_list[s_idx]
    Action = s_list[s_idx+1]
    Object = s_list[s_idx+2] #more if/else to validate Object contraints
    Price = s_list[s_idx+3] #more if/else to extract 2.0 if we get @2.0

    print("Subject: {}, Action: {}, Object: {}, Price: {}".format(Subject, Action, Object, Price))



    How can I do this better? Possibly using re

    Continue reading...

Compartilhe esta Página