2016-10-09 3 views
0

Я пытаюсь автоматически сделать большой корпус в числовой список. Один номер в строке. Например, у меня есть следующие данные:создание текстового документа числовой список

Df.txt = 

In the years thereafter, most of the Oil fields and platforms were named after pagan “gods”. 
We love you Mr. Brown. 
Chad has been awesome with the kids and holding down the fort while I work later than usual! The kids have been busy together playing Skylander on the XBox together, after Kyan cashed in his $$$ from his piggy bank. He wanted that game so bad and used his gift card from his birthday he has been saving and the money to get it (he never taps into that thing either, that is how we know he wanted it so bad). We made him count all of his money to make sure that he had enough! It was very cute to watch his reaction when he realized he did! He also does a very good job of letting Lola feel like she is playing too, by letting her switch out the characters! She loves it almost as much as him. 
so anyways, i am going to share some home decor inspiration that i have been storing in my folder on the puter. i have all these amazing images stored away ready to come to life when we get our home. 
With graduation season right around the corner, Nancy has whipped up a fun set to help you out with not only your graduation cards and gifts, but any occasion that brings on a change in one's life. I stamped the images in Memento Tuxedo Black and cut them out with circle Nestabilities. I embossed the kraft and red cardstock with TE's new Stars Impressions Plate, which is double sided and gives you 2 fantastic patterns. You can see how to use the Impressions Plates in this tutorial Taylor created. Just one pass through your die cut machine using the Embossing Pad Kit is all you need to do - super easy! 
If you have an alternative argument, let's hear it! :) 

Сначала я прочитал текст, используя команду readLines:

text <- readLines("Df.txt", encoding = "UTF-8") 

Во-вторых, я получаю весь текст в строчные буквы, и я удалить ненужные расстояние:

## Lower cases input: 
lower_text <- tolower(text) 
## removing leading and trailing spaces: 
Spaces_remove <- str_trim(lower_text) 

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

"In the years thereafter, most of the Oil fields and platforms were named after pagan “gods”." = 1 
"We love you Mr. Brown." = 2 
... 
"If you have an alternative argument, let's hear it! :)" = 6 

Любые идеи?

+0

Что значит «назначить ему число». Использовать кадр данных с двумя столбцами? – hrbrmstr

+1

Что-то вроде 'setNames (txt, 1: length (txt))' или 'as.list (txt)'? – Jaap

+0

Я думаю, это будет as.list (txt). Как вы, ребята, видите в конечном коде, каждая строка назначает номер. Ура! –

ответ

1

Вы уже сделать своего рода имеют числовые строки # ассоциации с вектором (она индексируется численно), но ...

text_input <- 'In the years thereafter, most of the Oil fields and platforms were named after pagan “gods”. 
We love you Mr. Brown. 
Chad has been awesome with the kids and holding down the fort while I work later than usual! The kids have been busy together playing Skylander on the XBox together, after Kyan cashed in his $$$ from his piggy bank. He wanted that game so bad and used his gift card from his birthday he has been saving and the money to get it (he never taps into that thing either, that is how we know he wanted it so bad). We made him count all of his money to make sure that he had enough! It was very cute to watch his reaction when he realized he did! He also does a very good job of letting Lola feel like she is playing too, by letting her switch out the characters! She loves it almost as much as him. 
so anyways, i am going to share some home decor inspiration that i have been storing in my folder on the puter. i have all these amazing images stored away ready to come to life when we get our home. 
With graduation season right around the corner, Nancy has whipped up a fun set to help you out with not only your graduation cards and gifts, but any occasion that brings on a change in one\'s life. I stamped the images in Memento Tuxedo Black and cut them out with circle Nestabilities. I embossed the kraft and red cardstock with TE\'s new Stars Impressions Plate, which is double sided and gives you 2 fantastic patterns. You can see how to use the Impressions Plates in this tutorial Taylor created. Just one pass through your die cut machine using the Embossing Pad Kit is all you need to do - super easy! 
If you have an alternative argument, let\'s hear it! :)' 

library(dplyr) 
library(purrr) 
library(stringi) 

textConnection(text_input) %>% 
    readLines(encoding="UTF-8") %>% 
    stri_trans_tolower() %>% 
    stri_trim() -> corpus 

# data frame with explicit line # column 
df <- data_frame(line_number=1:length(corpus), text=corpus) 

# list with an explicit line number field 
lst <- map(1:length(corpus), ~list(line_number=., text=corpus[.])) 

# implicit list numeric ids 
as.list(corpus) 

# explicit list numeric id's (but they're really string keys) 
setNames(as.list(corpus), 1:length(corpus)) 

# named vector 
set_names(corpus, 1:length(corpus)) 

Есть целый множество из R пакетов, которые значительно облегчат бремя обработки текста/NLP ОПС. Выполнение этой работы вне их, вероятно, будет изобретать колесо. В списке CRAN NLP Task View перечислены многие из них.

+0

Большое спасибо за код и советы @hrbmstr, последнее. Я хочу, чтобы объект был в классе числовым, а не в списке. Я пытаюсь передать его в n-граммовую функцию для предсказания слов и работает только с вводом как числовым. Cheers –

+2

Возможно, вам стоит вернуться к исходному вопросу и поставить в _all_ необходимую информацию для людей, чтобы попытаться помочь вам. То, что вы только что ввели в свой комментарий, неясно. Какое «предсказание». Что такое «числовые»? Вы знаете, что можете делать 'as.numeric (vector_of_characters)' и получать номера обратно, правильно? Вы не совсем четко сформулировали свою потребность. – hrbrmstr

 Смежные вопросы

  • Нет связанных вопросов^_^