Spacy Rule based Matching to identify the words which have relationship with money/date in python

Viewed 422

I am new to spacy. I try to spot the words which have relationship with money or date.

import spacy
from spacy import displacy

nlp = spacy.load("en_core_web_sm")

doc=nlp("""The client is look at 5x income. He has a loan with $5000 outstanding which can be repaid now this will free up $50 monthly. Credit card outstanding of $60 client will look to pay this off with bonus in September.""")

displacy.render(doc,style="ent",jupyter=True)
displacy.render(doc,style="dep",jupyter=True)

enter image description here According to dependency output (not shown here), I try to search for words to refer to money and date (for example, $60 -> credit card outstanding). After reading lots of tutorials (including spacy) and blogs, I think I should use the dependency rules based match. However, it seems that I need to specify the number (money) in the pattern with a specific structure (for example, a pattern structure for $10000). Can we create a pattern for any money entity?

Also in order to build the pattern, can someone help me build a pattern for $60 and $5000? Thank you

1 Answers

You may use something like this:

import spacy
nlp = spacy.load("en_core_web_sm")

# Merge noun phrases and entities for easier analysis
nlp.add_pipe("merge_entities")
nlp.add_pipe("merge_noun_chunks")

doc=nlp("""The client is look at 5x income. He has a loan with $5000 outstanding which can be repaid now this will free up $50 monthly. Credit card outstanding of $60 client will look to pay this off with bonus in September.""")

for token in doc:
    if token.ent_type_ == "MONEY":
        # We have an attribute and direct object, so check for subject
        if token.dep_ in ("attr", "dobj"):
            subj = [w for w in token.head.lefts if w.dep_ == "nsubj" or w.dep_ == "amod"]
            if subj:
                print(subj[0], "-->", token)
        # We have a prepositional object with a preposition
        elif token.dep_ == "pobj" and token.head.dep_ == "prep":
            print(token.head.head, "-->", token)

Output:

a loan --> 5000
this --> 50
Credit card --> 60
Related