Regex отлично подходит для тестера, но не в коде Python - PullRequest
0 голосов
/ 17 июня 2020

Я хотел бы удалить текст между строками «Сведения о критериях» и «\ n {Некоторое число} \ n» или «\ nPage {Некоторое число} \ n». Мой код ниже:

test = re.search(r'Criteria Details[\w\s\S]*?(\n[0-9]+\n|\nPAGE [0-9]+\n)', input_text)
print(test)
input_text = re.sub(r'Criteria Details[\w\s\S]*?(\n[0-9]+\n|\nPAGE [0-9]+\n)', ' ', input_text, flags=re.IGNORECASE)

Это работает с regex101 для строки ниже, поскольку я вижу, что фрагмент между «Criteria Details» и «88» обнаружен, но .search () в моем code ничего не возвращает, и в .sub () ничего не заменяется. Я что-то упустил?

cyclobenzaprine oral tablet 10 mg, 5 mg,
7.5 mg

PA Criteria

Criteria Details

N/A

N/A

other

N/A

Exclusion
Criteria

Required
Medical
Information

Prescriber
Restrictions

Coverage
Duration

Other Criteria

Age Restrictions  Patients aged less than 65 years, approve. Patients aged 65 years and older,

End of the Contract Year

PA does NOT apply to patients less than 65 yrs of age. High Risk
Medications will be approved if ALL of the following are met: a. Patient
has an FDA-approved diagnosis or CMS-approved compendia accepted
indication for the requested high risk medication AND b.  the prescriber
has completed a risk assessment of the high risk medication for the patient
and has indicated that the benefits of the requested high risk medication
outweigh the risks for the patient AND c.Prescriber has documented that
s/he discussed risks and potential side effects of the medication with the
patient AND d. if patient is taking conconmitantly a muscle relaxant with
an opioid, the prescriber indicated that the benefits of the requested
combination therapy outweigh the risks for the patient.

Indications

All Medically-accepted Indications.

Off-Label Uses

N/A



88


Updated 06/2020

Я ожидал, что результат будет примерно таким:

cyclobenzaprine oral tablet 10 mg, 5 mg,
7.5 mg

PA Criteria



Updated 06/2020

Ответы [ 2 ]

0 голосов
/ 18 июня 2020

Я разобрался. При использовании Pdfminer для синтаксического анализа PDF-файла в текст на самом деле нет новых строк после номера страницы, но они преобразуются в новые строки, если я копирую и вставляю вывод на веб-сайт регулярного выражения или Stackoverflow. В итоге я использовал \ s вместо \ n для обнаружения конечных пробелов после номеров страниц.

0 голосов
/ 17 июня 2020

Понятно, глупая ошибка. Измените свой код на этот

input_text = re.sub(r'Criteria Details[\w\s\S]*?(\n[0-9]+\n|\nPAGE [0-9]+\n)', ' ', input_text, flags=re.IGNORECASE)
print(input_text)

Где вы пошли не так, это

input_text = re.sub(r'Criteria Details[\w\s\S]*?(\n[0-9]+\n|\nPAGE [0-9]+\n)', ' ', input_text, flags=re.IGNORECASE) # This is the necessary replacement well done
test = re.search(r'Criteria Details[\w\s\S]*?(\n[0-9]+\n|\nPAGE [0-9]+\n)', input_text) # This extracts a pattern which will never be found because you already removed it
print(test) # The result of the previous line which would never be found

Надеюсь, это поможет! У всех бывают плохие дни ?

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