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.
3 Réponses :
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.
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".
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)
stackoverflow.com/questions/54481198 /…
Veuillez être plus précis sur le problème. Avec quelle partie vous battez-vous?