найти инициализмы из сокращений в тексте - PullRequest
0 голосов
/ 13 апреля 2020

У меня есть список сокращений, и я хочу найти их определения в тексте и затем поместить их в словарь. Я сделал код, но он жестко запрограммирован и не дает желаемого результата. Я хочу, чтобы мой конечный результат был примерно таким.

 {'NBA': ' National Basketball Association', 'NCAA': 'National Collegiate Athletic Association'}

code:

dict = {}
full_form = ' '
s = " NBA  comes from the words National Basketball Association is a men's professional basketball league in North America, composed of 30 teams. On the other hand NCAA stands for The National Collegiate Athletic Association"


acro = ['NBA', 'NCAA']

for char in range(len(acro)):
    for n,word in enumerate (list_str):
        if acro[char][0] == word[0] and word not in acro:
            full_form += word + ' '
            print(full_form)
            if acro[char][1] == list_str[n+1][0] and word not in acro:
                print(list_str[n+1])
                full_form += list_str[n+1] + ' '
                if acro[char][2] == list_str[n+2][0] and word not in acro:
                    full_form += list_str[n+2] + ''
                    d[acro[char]] = full_form
print(d)
out: {'NBA': ' National Basketball Association', 'NCAA': ' National Basketball AssociationNorth National National North National Collegiate Athletic'}

Любая помощь в том, как достичь ожидаемого результата в pythoni c wat, будет весьма полезной. оценили.

1 Ответ

1 голос
/ 13 апреля 2020

Вот простой пример того, как вы можете применять регулярные выражения:

import re

s = " NBA  comes from the words National Basketball Association is a men's professional basketball league in North America, composed of 30 teams. On the other hand NCAA stands for The National Collegiate Athletic Association"
acro = ['NBA', 'NCAA', 'STFU']

patterns = [f'({a}).+?({" ".join(c + "[a-z]+" for c in a)})(?: |$)' for a in acro]
# python 3.8
result = dict(m.groups() for p in patterns if (m := re.search(p, s)))
# lower versions
result = dict(m.groups() for m in (re.search(p, s) for p in patterns) if m)

Здесь - это пример регулярного выражения, которое будет сгенерировано для 'NCAA':

(NCAA).+(N[a-z]+ C[a-z]+ A[a-z]+ A[a-z]+)(?: |$)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...