Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract list of words with specific character from string using regex in Python

I have a string contain words, each word has its own token (eg. NN/NNP/JJ etc). I want to take specific repeat words that contain NNP token. My code so far:

import re

sentence = "Rapunzel/NNP Sheila/NNP let/VBD down/RP her/PP$ long/JJ golden/JJ hair/NN in Yasir/NNP"

tes = re.findall(r'(\w+)/NNP', sentence)
print(tes)

The result of the code:

['Rapunzel', 'Sheila', 'Yasir']

As we see, there are 3 words contain NNP those are Rapunzel/NNP Sheila/NNP (appear next to each other) and Yasir/NNP (seperate by words to other NNP words). My problem is I need to sperate the word with repeat NNP and the other. My expected result is like :

['Rapunzel/NNP', 'Sheila/NNP'], ['Yasir/NNP']

What is the best way to perform this task, thanks.

like image 302
ytomo Avatar asked Feb 04 '23 16:02

ytomo


2 Answers

Match the groups as simple strings, and then split them:

>>> [m.split() for m in re.findall(r"\w+/NNP(?:\s+\w+/NNP)*", sentence)]
[['Rapunzel/NNP', 'Sheila/NNP'], ['Yasir/NNP']]
like image 62
Tim Pietzcker Avatar answered Feb 07 '23 06:02

Tim Pietzcker


You can get very close to your expected outcome using a different capture group.

>>> re.findall(r'((?:\w+/NNP\s*)+)', sentence)
['Rapunzel/NNP Sheila/NNP ', 'Yasir/NNP']

Capture group ((?:\w+/NNP\s*)+) will group all the \w+/NNP patterns together with optional spaces in between.

like image 39
anubhava Avatar answered Feb 07 '23 05:02

anubhava