1
votes

Recherche de toutes les occurrences d'une liste de mots dans un texte à l'aide de Python Regex

J'ai besoin de trouver toutes les occurrences d'une liste de mots dans un texte à l'aide de regex. Par exemple, étant donné les mots:

['i', 'I', 'My', 'i', 'i', 'my']

et certains

re.findall(r"(?=("+'|'.join(words)+r"))", text, flags=re.IGNORECASE))

devraient renvoyer result = ["I", "My" , "my"]

J'utilise ceci:

re.findall(r"'|'.join(words))", text,flags=re.IGNORECASE))

Mais il renvoie une liste vide.

Aussi si j'utilise ceci:

text = 'A book is on the table. I have a book on the table. My book is on the table. There is my book on the table.'

returns:

words = {'i', 'me', 'my'}

ce qui est incorrect.


2 commentaires

stackoverflow.com/questions/54481198 /…


Veuillez être plus précis sur le problème. Avec quelle partie vous battez-vous?


3 Réponses :


1
votes

Il y a un problème dans la façon dont vous définissez l'expression régulière. Vous ne joignez pas les mots, vous utilisez une expression régulière "'|' .join (words)" , qui ne mène à aucune correspondance.

>>> re.findall(r"\b({})\b".format('|'.join(words)), text[0], flags=re.IGNORECASE)
['I', 'My', 'my']

Vous pouvez réécrire comme

>>> x = r"'|'.join(words)"
>>> x
"'|'.join(words)"

Remarque \ b voici une frontière du monde qui correspond à la chaîne vide au début ou à la fin d'un mot nécessaire pour ne faire correspondre que les mots complets.


0 commentaires

1
votes
re.compile('|'.join(map(lambda x: '\\b' + x + '\\b', words)), 
           flags=re.IGNORECASE)
  .findall(text[0])
Putting \b on either side of words keeps "I" from matching things like "is".

0 commentaires

1
votes

Les expressions régulières sont très intéressantes. En règle générale, j'écris des regex que je peux lire N jours dans le futur. Voici comment je vais faire:

import re

words = ["I", "am", "my"]

text = ("A book is on the table. I have a book on the table. My book is on the table. There is my book on the table.")

# get values from my list, the can be preceded or exceeded by not a word e.g: Is it I?

pattern = r'\W.*?({})\W.*?'.format('|'.join(words))

s = re.findall(pattern, text, flags=re.IGNORECASE)

print(s)


0 commentaires