Как прочитать текстовый файл в R, который указывает номер страницы и абзацы на каждой странице - PullRequest
0 голосов
/ 09 октября 2018

Я прочитал файл .txt, используя readLines() в R. Я не указал номера строк (т.е. номера строк отображения) в файле txt.Файл txt находится в этой форме.

        page1:
       paragraph1:Banks were early adopters, but now the range of applications 
            and organizations using predictive analytics successfully have multiplied. Direct marketing and sales.
     Leads coming in from a company’s website can be scored to determine the probability of a 
                            sale and to set the proper follow-up priority. 
paragraph2: Campaigns can be targeted to the candidates most 
                        likely to respond. Customer relationships.Customer characteristics and behavior are strongly 
                        predictive of attrition (e.g., mobile phone contracts and credit cards). Attrition or “churn” 
                    models help companies set strategies to reduce churn rates via communications and special offers. 
                Pricing optimization. With sufficient data, the relationship between demand and price can be modeled for 
            any product and then used to determine the best pricing strategy.

Аналогично, на странице2 в файле .txt есть параграфы.

Но я не мог различить страницы и абзацы, так как .txt файл не различает страницы.Есть ли способ или предложение указать страницы и абзац в R.

Ответ, данный Эдвардом Карни , как раз для этого.Но если я не использую «абзац (№)», как определить абзац с помощью табуляции / пробела?

1 Ответ

0 голосов
/ 10 октября 2018

Этот метод использует функцию stripWhitespace из библиотеки tm, но, кроме этого, это базовая R.

Сначала прочитайте текст и найдите строки page#:, используя grep.

x <- readLines('text2.txt')
page_locs <- grep('page\\d:', x)
# add an element with the last line of the text plus 1
page_locs[length(page_locs)+1] <- length(x) + 1
# strip out the whitespace
x <- stripWhitespace(x)
# break the text into a list of pages, eliminating the `page#:` lines.
pages <- list()
# grab each page's lines into successive list elements
for (i in 1:(length(page_locs)-1)) {
  pages[[i]] <- x[(page_locs[i]+1):(page_locs[i+1]-1)]
}

Затем обработайте каждую страницу в виде списка абзацев для каждой страницы.

for (i in 1:length(pages)) {
    # get the locations for the paragraphs
    para_locs <- grep('paragraph\\d:', pages[[i]])
    # add an end element
    para_locs[length(para_locs) + 1] <- length(pages[[i]]) + 1
    # delete the paragraph marker
    curr_page <- gsub('paragraph\\d:','',pages[[i]])
    curr_paras <- list()
    # step through the paragraphs in each page
    for (j in 1:(length(para_locs)-1)) {
        # collapse the vectors for each paragraph
        curr_paras[[j]] <- paste(curr_page[para_locs[j]:(para_locs[j+1]-1)], collapse='')
        # delete leading spaces for each paragraph if desired
        curr_paras[[j]] <- gsub('^ ','',curr_paras[[j]])
    }
    # store the list of paragraphs back into the pages list
    pages[[i]] <- curr_paras
}

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

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