Python: How to find n-gram patterns in the text?
Question: I have a string which could be arbitrary long say

    
    
    s = 'Choose from millions of possibilities on Shaadi.com. Create your profile, search&contact; your special one.RegisterFree\xa0\xa0\xa0unsubscribing reply to this mail\xa0\n and 09times and this is limited time offer! and this is For free so you are saving cash'
    

I have a list of spam words which could be like

    
    
    p_words = ['cash', 'for free', 'limited time offer']
    

All I want to know if there pattern exists in the input text and how many
times?

It becomes simple when it has just one word

    
    
    import re
    p = re.compile(''.join[p_words])  # correct me if I am wrong here
    m = p.match(s)  
    

but it could be a `bi-gram, tri-gram or n-gram`

How do we approach this?


Answer: 
    p = re.compile('|'.join(re.escape(w) for w in p_words))
    

`p` will then match any of the strings in `p_words`.

