R: разбор текстового файла цитат / разбиение на абзацы - PullRequest
0 голосов
/ 27 марта 2020

Я ищу R решение проблемы синтаксического анализа текстового файла цитат (как показано ниже), дающего data.frame с одним наблюдением за цитатой и переменными text и source, как описано ниже.

DIAGRAMS are of great utility for illustrating certain questions of vital statistics by
conveying ideas on the subject through the eye, which cannot be so readily grasped when
contained in figures.
--- Florence Nightingale, Mortality of the British Army, 1857

To give insight to statistical information it occurred to me, that making an
appeal to the eye when proportion and magnitude are concerned, is the best and
readiest method of conveying a distinct idea. 
--- William Playfair, The Statistical Breviary (1801), p. 2


Regarding numbers and proportions, the best way to catch the imagination is to speak to the eyes.
--- William Playfair, Elemens de statistique, Paris, 1802, p. XX.

The aim of my carte figurative is to convey promptly to the eye the relation not given quickly by numbers requiring mental calculation.
--- Charles Joseph Minard

Здесь каждая цитата является абзацем, отделенным от следующего "\n\n". В пределах абзаца все строки до одного начала --- составляют text, а следующие --- - это source.

Я думаю, я мог бы решить эту проблему, если бы мог сначала сначала разбить текстовые строки в абзацы (разделенные '\\n\\n+' (2 или более пустых строк), но у меня возникают проблемы с этим.

Ответы [ 3 ]

2 голосов
/ 27 марта 2020

Если исходный текст загружен в rawText переменную

library(stringr)

strsplit(rawText, "\n\n")[[1]] %>% 
  str_split_fixed("\n--- ", 2) %>% 
  as.data.frame() %>% 
  setNames(c("text", "source"))
1 голос
/ 27 марта 2020

При условии, что ваш текстовый файл quote.txt в рабочем каталоге.

R base решение: разделить его 2 раза: (1) на \n\n и (2) на ---, затем объединить в фрейм данных.

quote <- readLines("quote.txt")
quote <- paste(quote, collapse = "\n")

DF <- strsplit(unlist(strsplit(quote, "\n\n")), "---")
DF <- data.frame(text= trimws(sapply(DF, "[[", 1)), 
           source = trimws(sapply(DF, "[[", 2)))

Вывод

DF
                                                                                                                                                                                                                                                                                 # text
# 1     DIAGRAMS are of great utility for illustrating certain questions of vital statistics by\nconveying ideas on the subject through the eye, which cannot be so readily grasped when\ncontained in figures.
# 2 To give insight to statistical information it occurred to me, that making an\nappeal to the eye when proportion and magnitude are concerned, is the best and\nreadiest method of conveying a distinct idea.
# 3                                                                                                           Regarding numbers and proportions, the best way to catch the imagination is to speak to the eyes.
# 4                                                                     The aim of my carte figurative is to convey promptly to the eye the relation not given quickly by numbers requiring mental calculation.
#                                                          source
# 1     Florence Nightingale, Mortality of the British Army, 1857
# 2       William Playfair, The Statistical Breviary (1801), p. 2
# 3 William Playfair, Elemens de statistique, Paris, 1802, p. XX.
# 4                                         Charles Joseph Minard
1 голос
/ 27 марта 2020

Это должно сделать большую часть того, что вам нужно для достижения. Я предполагаю, что у вас уже есть файл в символьном векторе длиной 1 с именем txt:

library(tidyverse)

txt                                             %>% 
strsplit("\n{2,5}")                             %>% 
unlist()                                        %>% 
lapply(function(x) unlist(strsplit(x, "--- "))) %>%
{do.call("rbind", .)}                           %>%
as.data.frame(stringsAsFactors = FALSE)         %>%
setNames(c("Text", "Source"))                    ->
df

Если затем очистить текст, заменив символы новой строки пробелами, вы получите следующее:

df$Text <- gsub("\n", " ", df$Text)
as_tibble(df)
#> # A tibble: 4 x 2
#>   Text                                              Source                             
#>   <chr>                                             <chr>                              
#> 1 "DIAGRAMS are of great utility for illustrating ~ Florence Nightingale, Mortality of~
#> 2 "To give insight to statistical information it o~ William Playfair, The Statistical ~
#> 3 "Regarding numbers and proportions, the best way~ William Playfair, Elemens de stati~
#> 4 "The aim of my carte figurative is to convey pro~ Charles Joseph Minard 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...