2
votes

Trouver deux mots se produisant avant un index dans une chaîne en utilisant python

Étant donné le texte, je veux trouver des mots se produisant avant

19 
81

la sortie inconnue est

text="the women marathon unknown introduced at the summer olympics los angeles usa and unknown won"  
items=re.finditer('unknown',text).  #as there are 2 unknown
for i in items:  
   print(i.start()) #to get index of 2 unknown

Maintenant, comment extraire les mots se produisant avant les deux inconnues séparément?
Pour la première inconnue, je devrais obtenir les femmes.
et pour le deuxième inconnu, je devrais avoir les USA, et


5 commentaires

publier le résultat attendu


Voulez-vous utiliser uniquement re ? Cela peut également être fait avec d'autres méthodes.


Pas forcément re. Quelles sont toutes les autres méthodes?


J'ai spécifié dans la question d'extraire deux mots avant inconnu


Pourquoi devriez-vous obtenir the, women et non women marathon ?


3 Réponses :


1
votes

Cette expression peut être proche de ce que l'on pourrait souhaiter ici:

import re

regex = r"([\s\S]*?)(unknown)"

test_str = "the women marathon unknown introduced at the summer olympics los angeles usa and unknown won"

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

Test avec re.findall

import re

regex = r"([\s\S]*?)(unknown)"

test_str = "the women marathon unknown introduced at the summer olympics los angeles usa and unknown won"

print(re.findall(regex, test_str, re.MULTILINE))

Test avec re. finditer

([\s\S]*?)(\bunknown\b)

L'expression est expliquée dans le panneau supérieur droit de cette démo , si vous souhaitez l'explorer / la simplifier / la modifier, et dans ce lien , vous pouvez voir comment il correspondrait à certains exemples d'entrées étape par étape, si vous le souhaitez.


0 commentaires

1
votes

Approche courte:

women marathon 
usa and 

Le résultat:

import re

text = "the women marathon unknown introduced at the summer olympics los angeles usa and unknown won"
matches = re.finditer('(\S+\s+){2}(?=unknown)', text)
for m in matches:
   print(m.group())


1 commentaires

Comment faire pour inclure le mot «inconnu»?



1
votes

Version sans re , avec itertools.groupby ( doc ):

['women', 'marathon']
['usa', 'and']

Impressions:

from itertools import groupby

text="the women marathon unknown introduced at the summer olympics los angeles usa and unknown won"

for v, g in groupby(text.split(), lambda k: k=='unknown'):
    if v:
        continue
    l = [*g]
    if len(l) > 1:
        print(l[-2:])


0 commentaires