É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
3 Réponses :
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)))
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))
([\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.
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())
Comment faire pour inclure le mot «inconnu»?
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:])
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, womenet nonwomen marathon?