RegEx: Find lists of words containing specific string - Python

Viewed 341

I'm looking to find the words containing any of the following sequences: 'tion', 'ex' 'ph' 'ost', 'ist', 'ast'.

Here is my function so far:

def latin_ish_words(text):
        return re.findall('tion|ex|ph|ost|ist|ast+\b', text, re.I))

However, this is only returning the specific sequence rather than the full words.

Example 1: latin_ish_words("This functions as expected") returns ['tion', 'ex'], whereas I am looking for ["functions", "expected"].

Example 2: text = 'Philosophy ex nihilo existed in the past' returns ['Ph', 'ph', 'ex', 'ex'], whereas I am looking for ['Philosophy', 'ex', 'existed', 'past']

Looking at the official Re documentation, I thought '\b' returned the full word?

Any suggestions?

3 Answers

You can try capture the prefix and post fix of the word using [a-z]*.

def latin_ish_words(text):
    return re.findall(r'\b([a-z]*(tion|ex|ph|ost)[a-z]*)\b', text, re.I)

In [1]: latin_ish_words("Philosophy ex nihilo existed in the past")
Out[1]: [('Philosophy', 'ph'), ('ex', 'ex'), ('existed', 'ex')]

The words you are trying to capture are first element of each tuple in the result list.

Maybe splitting the sentence and checking each word individually?

import re

def latin_ish_words(text):
    words = text.split(' ')
    matched_words = []

    for word in words:
        if re.findall('tion|ex|ph|ost', word, re.I):
            matched_words.append(word)

    return matched_words

You can try this:

import re
def latin_ish_words(text):
        return re.findall(r'(\w*(?:tion|ex|ph|ost|ast)\w*)', text, re.I)

text = 'Philosophy ex nihilo existed in the past.'
latin_ish_words(text)

It gives:

['Philosophy', 'ex', 'existed', 'past']

(?: ) indicates a non-capturing group i.e. a pattern that should be matched but should not be returned by itself as one of re.findall() results.

Related