Как я могу извлечь заказанные вопросы и ответы из блока простого текста - PullRequest
2 голосов
/ 30 мая 2019

Вопросы также доступны для простого текста. Я хочу иметь возможность использовать PHP, Regex . Однако, поскольку моей информации о Regex недостаточно, я попытался сделать это с помощью функции PHP.

Пример простого текста: (начиная с 12-го вопроса -> 15. вопрос, здесь всего 4 вопроса)

12. 47-летний мужчина жалуется на частичную потерю верхних зубов. Медицинский анамнез пациента указывает на потерю зубов из-за травмы. выдержал 3 месяца назад. 11 и 12 потеряны. 13, 21 и 22 разрушено на 2/3 и восстановлено с пломбами. Окклюзия ортогнатическая. Какая конструкция зубного протеза будет оптимальной для этого пациента, рассматривая его занятие в качестве лектора? A.Porcelain-конденсированные с металлом зубной мост B.Plastic зубной мост C.Casp-retained (bugel) съемный частичный протез с насадками D. съемный частичный ламинарный зубной протез для верхней челюсти E.Swaged-паяный металлический зубной мост с граненая промежуточная часть 13. У 7-летнего мальчика диагностирован Демический паротит (эпидемический паротит). Назовите наиболее похожее осложнение этого Болезнь: A. Орхит B. Колит C. Дерматит D. Пневмония E. Холецистит 14. Во время профилактического осмотра мужчина 40 лет представлены следующие изменения: краевая десна увеличена, в форме тора, синюшный, слегка кровоточащий при прикосновении к зубному зонд; боли нет Окрашивание десен йодом Люголя решение приводит к светло-коричневой окраске слизистой оболочки. Сделать Диагноз: А. Хронический катаральный гингивит Б. Острый катаральный гингивит C. Обострение хронического катарального гингивита D. Хроническая гипертрофия гингивит E. общий периодонтит 15. 4-летний мальчик был поставлен диагноз: острый гнойный периостит верхней челюсти происходящий из 64 зуба. Выберите оптимальную тактику лечения: A. Удаление 64 зубов, периостеотомия, фармакотерапия B. 64 удаление зуба, противовоспалительная фармакотерапия C. Эндодонтологический лечение 64 зуба, противовоспалительная фармакотерапия D. Эндодонтологическое лечение 64 зуба, периостеотомия E. периостеотомия, противовоспалительная фармакотерапия

  • В начале каждого вопроса есть номер вопроса.
  • Вопросы обычно имеют 5 или 4 варианта

Что я сделал?

 function gettingQuestionAndOptions($string, $start, $end)
    {
        $string = " " . $string;
        $ini = strpos($string, $start);
        if ($ini == 0) return "";
        $ini += strlen($start);
        $len = strpos($string, $end, $ini) - $ini;

        return substr($string, $ini, $len);
    }

Как мне его использовать?

if (gettingQuestionAndOptions($text, '?', "A. ")) {

    $parsedQuestion = gettingQuestionAndOptions($text, '', "?");
    $parsedA = gettingQuestionAndOptions($text, 'A. ', "B. ");
    $parsedB = gettingQuestionAndOptions($text, 'B. ', "C. ");
    $parsedC = gettingQuestionAndOptions($text, 'C. ', "D. ");
    $endQuestion = "?";

} else if (gettingQuestionAndOptions($text, ':', "A. ")) {

    $parsedQuestion = gettingQuestionAndOptions($text, '', ":");
    $parsedA = gettingQuestionAndOptions($text, 'A. ', "B. ");
    $parsedB = gettingQuestionAndOptions($text, 'B. ', "C. ");
    $parsedC = gettingQuestionAndOptions($text, 'C. ', "D. ");
    $endQuestion = ":";

} else {
}

Результат:

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


  1. Как я могу сделать это лучше? Или где моя вина?
  2. Могу ли я получить более правильные данные с помощью Regex?

1 Ответ

1 голос
/ 30 мая 2019

Предполагая, что ваш текст всегда начинается с цифры, группировать их должно быть простым делом: просто отслеживать текущий вопрос, который вы задаете, а затем искать следующий.Это поможет уменьшить количество ложных срабатываний.

<?php
$data = "12.A 47-year-old man complains of partial loss of his upper teeth. The patient’s medi- cal history states loss of teeth due to trauma sustained 3 months ago. 11 and 12 are lost. 13, 21, and 22 are destroyed by 2/3 and restored with?llings. Occlusion is orthognathic. What denture construction would be optimal for this patient, considering his occupation as a lecturer? A.Porcelain-fused-to-metal dental bridge B.Plastic dental bridge C.Clasp-retained (bugel) removable partial denture with attachments D.Removable partial laminar denture for the upper jaw E.Swaged-soldered metal dental bridge with faceted intermediate part 13.A 7-year-old boy is diagnosed with epi- demic parotitis (mumps). Name the most li- kely complication of this disease: A.Orchitis B.Colitis C.Dermatitis D.Pneumonia E.Cholecystitis14.During preventive examination a 40-year- old man presents with the following changes: marginal gingiva is enlarged, torus-shaped, cyanotic, slightly bleeding when touched wi- th a dental probe; there is no pain. Staining the gums with Lugol’s iodine solution results in light-brown coloring of mucosa. Make the diagnosis: A.Chronic catarrhal gingivitis B.Acute catarrhal gingivitis C.Exacerbation of chronic catarrhal gingivitis D.Chronic hypertrophic gingivitis E.Generalized periodontitis 15.A 4-year-old boy has been diagnosed wi- th acute purulent periostitis of the upper jaw originating from the 64 tooth. Choose the optimal treatment tactics: A.The 64 tooth extraction, periosteotomy, pharmacotherapy B.The 64 tooth extraction, anti-in?ammatory pharmacotherapy C.Endodontological treatment of the 64 tooth, anti-in?ammatory pharmacotherapy D.Endodontological treatment of the 64 tooth, periosteotomy E.Periosteotomy, anti-in?ammatory pharmacotherapy";
$questions = [];
$question_num = 12;
$previous_question_start = 0;
while (true) {
    $question_start = strpos($data, "$question_num.", $previous_question_start);
    $question_end = strpos($data, (++$question_num) . ".", $question_start);
    if ($question_end === false) {
        // no more matches, this is the last question
        $questions[] = substr($data, $question_start);
        break;
    }
    $questions[] = substr($data, $question_start, $question_end - $question_start);
    $previous_question_start = $question_start;
}

На данный момент у вас есть каждый вопрос в элементе массива, поэтому ищите ответы в каждом из них, используя ту же технику.Мы сохраним наши результаты в новом массиве.

$questions_answers = [];
$answer_choices = ["A", "B", "C", "D", "E"];
foreach ($questions as $q) {
    $qa = [];
    $qa["question"] = substr($q, 0, strpos($q, "$answer_choices[0]."));
    $previous_answer_start = 0;
    foreach ($answer_choices as $i=>$a) {
        $answer_start = strpos($q, $answer_choices[$i]. ".", $previous_answer_start);
        if (empty($answer_choices[$i + 1])) {
            // end of the array, this is the last answer
            $qa["answers"][] = substr($q, $answer_start);
            break;
        }
        $answer_end = strpos($q, $answer_choices[$i + 1] . ".", $answer_start);
        $qa["answers"][] = substr($q, $answer_start, $answer_end - $answer_start);
        $previous_answer_start = $answer_start;
    }
    $questions_answers[] = $qa;
}

print_r($questions_answers);

Вывод:

Array
(
    [0] => Array
        (
            [question] => 12.A 47-year-old man complains of partial loss of his upper teeth. The patient’s medi- cal history states loss of teeth due to trauma sustained 3 months ago. 11 and 12 are lost. 13, 21, and 22 are destroyed by 2/3 and restored with?llings. Occlusion is orthognathic. What denture construction would be optimal for this patient, considering his occupation as a lecturer? 
            [answers] => Array
                (
                    [0] => A.Porcelain-fused-to-metal dental bridge 
                    [1] => B.Plastic dental bridge 
                    [2] => C.Clasp-retained (bugel) removable partial denture with attachments 
                    [3] => D.Removable partial laminar denture for the upper jaw 
                    [4] => E.Swaged-soldered metal dental bridge with faceted intermediate part 
                )

        )

    [1] => Array
        (
            [question] => 13.A 7-year-old boy is diagnosed with epi- demic parotitis (mumps). Name the most li- kely complication of this disease: 
            [answers] => Array
                (
                    [0] => A.Orchitis 
                    [1] => B.Colitis 
                    [2] => C.Dermatitis 
                    [3] => D.Pneumonia 
                    [4] => E.Cholecystitis
                )

        )

    [2] => Array
        (
            [question] => 14.During preventive examination a 40-year- old man presents with the following changes: marginal gingiva is enlarged, torus-shaped, cyanotic, slightly bleeding when touched wi- th a dental probe; there is no pain. Staining the gums with Lugol’s iodine solution results in light-brown coloring of mucosa. Make the diagnosis: 
            [answers] => Array
                (
                    [0] => A.Chronic catarrhal gingivitis 
                    [1] => B.Acute catarrhal gingivitis 
                    [2] => C.Exacerbation of chronic catarrhal gingivitis 
                    [3] => D.Chronic hypertrophic gingivitis 
                    [4] => E.Generalized periodontitis 
                )

        )

    [3] => Array
        (
            [question] => 15.A 4-year-old boy has been diagnosed wi- th acute purulent periostitis of the upper jaw originating from the 64 tooth. Choose the optimal treatment tactics: 
            [answers] => Array
                (
                    [0] => A.The 64 tooth extraction, periosteotomy, pharmacotherapy 
                    [1] => B.The 64 tooth extraction, anti-in?ammatory pharmacotherapy 
                    [2] => C.Endodontological treatment of the 64 tooth, anti-in?ammatory pharmacotherapy 
                    [3] => D.Endodontological treatment of the 64 tooth, periosteotomy 
                    [4] => E.Periosteotomy, anti-in?ammatory pharmacotherapy
                )

        )

)

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

В качестве примечания, я замечаю, что вы теряете такие символы, как "fl" (f / l ligature) и "if" (f /я связываю.) Если вы извлекаете эту информацию из базы данных или веб-страницы, убедитесь, что вы правильно работаете с символами UTF-8.

...