Код: Выделить всё
Detected Names in Text: ['garcía', 'lópez']
Detected Names in Text: ['j. jesus orozco alfaro']
Detected Names in Text: ['josé guadarrama márquez', 'josé guadarrama']
Detected Names in Text: ['pedro sánchez', 'josé manuel albares', 'pablo iglesias']
Код: Выделить всё
Detected Names in Text: ['garcía']
Detected Names in Text: ['j. jesus orozco alfaro']
Detected Names in Text: ['josé guadarrama márquez']
Detected Names in Text: ['pedro sánchez']
Код: Выделить всё
import spacy
from spacy.matcher import Matcher
nlp = spacy.load("es_core_news_lg")
texts = [
"El Sr. García habló en la sesión. También estuvo presente el Senador López y la Diputada Martínez.",
"PRESIDENCIA DEL C. SENADOR J. JESUS OROZCO ALFARO",
" -ER C. José Guadarrama Márquez: el contrabando del dia, José Guadarrama Márquez",
"El presidente Pedro Sánchez y el Ministro de Asuntos Exteriores José Manuel Albares se reunieron con el Senador Pablo Iglesias."
]
texts = [text.lower() for text in texts]
matcher = Matcher(nlp.vocab)
patterns = [
[{"LOWER": "el"}, {"LOWER": "c"}],
[{"LOWER": "el"}, {"LOWER": "sr"}],
[{"LOWER": "el"}, {"LOWER": "sra"}]
]
matcher.add("LEGISLATIVE_TITLES", patterns)
# Function to find a sequence of PER entities allowing one MISC
def find_per_sequence(doc, start_idx=0):
per_entities = []
misc_count = 0
for ent in doc[start_idx:].ents:
if ent.label_ == "PER":
per_entities.append(ent.text)
elif ent.label_ == "MISC" and misc_count < 1:
misc_count += 1
per_entities.append(ent.text)
else:
break # Should stop if any other entity or second MISC is encountered
return per_entities
for text in texts:
doc = nlp(text)
# Find matches
matches = matcher(doc)
# Extract the first match and its position
title_start = None
title_end = None
for match_id, start, end in matches:
title_start = start
title_end = end
break
# If a title was found, start searching for PER entities from that position
if title_start is not None:
names = find_per_sequence(doc, start_idx=title_end)
else:
names = find_per_sequence(doc)
# Output the detected names for each text
print(f"Detected Names in Text: {names}")
Я хочу изменить функцию find_per_sequence так, чтобы она возвращала только первую непрерывную последовательность объектов «PER». в тексте, игнорируя любые последующие объекты «PER» после обнаружения объекта другого типа. Предоставленная функция возвращает несколько имен или частей имен, и мне нужен способ гарантировать, что будет включено только имя или последовательность. Как мне этого добиться?
Подробнее здесь: https://stackoverflow.com/questions/789 ... with-spacy