Вытащить фрагмент текста

Рейтинг: 0Ответов: 1Опубликовано: 06.07.2023

В результате выполнения функции получаю ответ в виде очень длинной строки

t = '  Reading input spec file from \n\n1\n\n               U. S. Department of Commerce, U. S. Census Bureau\n\n              X-13ARIMA-SEATS monthly seasonal adjustment Method,\n                          Release Version 1.1 Build 58\n\n\n           This software application provides an enhanced version of\n             Statistics Canada\'s X-11-ARIMA extension (Dagum, 1980)\n                 of the X-11 variant of the Census Method II of\nARIMA Model:  (0 1 1)(0 1 1)\n   Nonseasonal differences: 1\n   Seasonal differences:    1\n                                              Standard\n Parameter                    Estimate          Errors\n -----------------------------------------------------\n Nonseasonal MA                                    \n   Lag  1                       0.4018         0.07887\n\n Seasonal MA                                       \n   Lag 12                       0.5569         0.07626\n\n Variance                       0.13481E-02\n SE of Var                      0.16657E-03\n -----------------------------------------------------\n\n Likelihood Statistics\n ------------------------------------------------------------------\n Number of observations (nobs)                                  144\n Effective number of observations (nefobs)                      131\n Number of parameters estimated (np)                              3\n Log likelihood                                            244.6965\n Transformation Adjustment                                -735.2943\n Adjusted Log likelihood (L)                              -490.5978\n AIC                                                       987.1956 \n AICC (F-corrected-AIC)                                    987.3845 \n Hannan Quinn                                              990.7005 \n BIC                                                       995.8211 \n ------------------------------------------------------------------\n\n QS Statistic for regARIMA Model Residuals (full series):             0.00\n                                                       (P-Value =     1.0000)\n\n QS Statistic for regARIMA Model Residuals :       2.31\n                                                       (P-Value =     0.3153)\n\n\n  At least one visually significant residual seasonal peaks has been\n  found in the spectral plot of the following series starting :\n\n          regARIMA model residuals (1 Seasonal peak(s))\n\n      10*LOG(SPECTRUM) of the regARIMA model residuals\n      Spectrum estimated from

Необходимо получить фрагмент текста, который начинается со слова 'ARIMA Model:' и заканчивается '(P-Value = 0.3153)'

ARIMA Model:  (0 1 1)(0 1 1)\n   Nonseasonal differences: 1\n   Seasonal differences:    1\n                                              Standard\n Parameter                    Estimate          Errors\n -----------------------------------------------------\n Nonseasonal MA                                    \n   Lag  1                       0.4018         0.07887\n\n Seasonal MA                                       \n   Lag 12                       0.5569         0.07626\n\n Variance                       0.13481E-02\n SE of Var                      0.16657E-03\n -----------------------------------------------------\n\n Likelihood Statistics\n ------------------------------------------------------------------\n Number of observations (nobs)                                  144\n Effective number of observations (nefobs)                      131\n Number of parameters estimated (np)                              3\n Log likelihood                                            244.6965\n Transformation Adjustment                                -735.2943\n Adjusted Log likelihood (L)                              -490.5978\n AIC                                                       987.1956 \n AICC (F-corrected-AIC)                                    987.3845 \n Hannan Quinn                                              990.7005 \n BIC                                                       995.8211 \n ------------------------------------------------------------------\n\n QS Statistic for regARIMA Model Residuals (full series):             0.00\n                                                       (P-Value =     1.0000)\n\n QS Statistic for regARIMA Model Residuals :       2.31\n                                                       (P-Value =     0.3153)

Сейчас получаю его с помощью следующего фрагмента кода:

t = t.split('ARIMA Model:')
t1 = t[1].split('At least')
ppp = 'ARIMA Model:' + t1[0]

Можно ли получить этот фрагмент более красивым способом? Или у такой задачи нет другого решения?

Ответы

▲ 0

Используйте регулярные выражения.

Например:

import re
res = re.search(r"(ARIMA Model[^\(]+\(P-Value[^\(]+\))", t).group(1)

res:

ARIMA Model Residuals :       2.31
                                                       (P-Value =     0.3153)

Или, если таких подстрок может быть несколько:

res = re.findall(r"(ARIMA Model[^\(]+\(P-Value[^\(]+\))", t)

res:

['ARIMA Model Residuals :       2.31\n                                                       (P-Value =     0.3153)']

С пробелами и переводами строки в найденной подстроке, думаю, разберетесь сами.

UPDATE

Кажется, у вас вывод имеет постоянную структуру, то можно сделать так

res2 = t.splitlines()[13:48]

без регулярок. то есть, разбить строку по переводам строк и выбрать нужные строки (индексы нашел опытным путём).