Я видел пару подобных вопросов, размещенных на SO по этой теме, но они, похоже, неправильно написаны (example) или на другом языке (example) ,Извлеките образец слов вокруг определенного слова, используя stringr в R
В моем сценарии я рассматриваю все, что окружает пустое пространство, чтобы быть словом. Смайлики, цифры, строки букв, которые на самом деле не слова, мне все равно. Я просто хочу получить некоторый контекст вокруг найденной строки, не прочитав весь файл, чтобы выяснить, является ли это допустимым.
Я попытался использовать следующее, но это занимает некоторое время, чтобы работать, если у вас есть длинный текстовый файл:
text <- "He served both as Attorney General and Lord Chancellor of England. After his death, he remained extremely influential through his works, especially as philosophical advocate and practitioner of the scientific method during the scientific revolution. Bacon has been called the father of empiricism.[6] His works argued for the possibility of scientific knowledge based only upon inductive and careful observation of events in nature. Most importantly, he argued this could be achieved by use of a skeptical and methodical approach whereby scientists aim to avoid misleading themselves. While his own practical ideas about such a method, the Baconian method, did not have a long lasting influence, the general idea of the importance and possibility of a skeptical methodology makes Bacon the father of scientific method. This marked a new turn in the rhetorical and theoretical framework for science, the practical details of which are still central in debates about science and methodology today. Bacon was knighted in 1603 and created Baron Verulam in 1618[4] and Viscount St. Alban in 1621;[3][b] as he died without heirs, both titles became extinct upon his death. Bacon died of pneumonia in 1626, with one account by John Aubrey stating he contracted the condition while studying the effects of freezing on the preservation of meat."
stringr::str_extract(text, "(.*?\\s){1,10}Verulam(\\s.*?){1,10}")
Я предполагаю, что есть много, гораздо быстрее/более эффективного способа, в котором для этого, да?
Вас интересует только первое совпадение строк? Я думаю, вы хотите больше, чем это. – fishtank
@fishtank Я бы хотел больше, чем первый, поэтому я подправил ответ ниже, чтобы использовать 'stringr :: str_extract_all' в отличие от' stringr :: str_extract' – brittenb