我有一個 txt 檔案的檔案夾,我想從中提取特定的文本并將它們單獨的列排列到一個新的資料框中。我為一個檔案撰寫了代碼,但我似乎無法將其編輯為一個回圈,該回圈將在我的檔案夾中的所有檔案中運行。
這是我的一個 txt 檔案的代碼:
clean_text <- as.data.frame(strsplit(text$text, '\\*' ), col.names = "text") %>%
mutate(text = str_replace_all(text, "\n", " "),
text = str_replace_all(text, "- ", ""),
text = str_replace_all(text,"^\\s", "")) %>%
filter(!text == " ") %>%
mutate(paragraphs = ifelse(grepl("^[[:digit:]]", text) == T, text, NA)) %>%
rename(category = text) %>%
mutate(category = ifelse(grepl("^[[:digit:]]", category) == T, NA, category)) %>%
fill(category) %>%
filter(!is.na(paragraphs)) %>%
mutate(paragraphs = strsplit(paragraphs, '^[[:digit:]]{1,3}\\.|\\t\\s[[:digit:]]{1,3}\\.')) %>%
unnest(paragraphs) %>%
mutate(paragraphs = strsplit(paragraphs, 'Download as PDF')) %>%
unnest(paragraphs) %>%
mutate(paragraphs = str_replace_all(paragraphs, "\t", "")) %>%
mutate(paragraphs = ifelse(grepl("javascript", paragraphs), "", paragraphs)) %>%
mutate(paragraphs = str_replace_all(paragraphs, "^\\s ", "")) %>%
filter(!paragraphs == "")
我如何把它變成一個回圈?我意識到有類似的問題,但沒有一個解決方案對我有用。在此先感謝您的幫助!
uj5u.com熱心網友回復:
將您的代碼放在一個函式中:
extract_info = function(file) {
## Add the code you need to read the text from the file
## Something like
## text <- readLines(file)
## or whatever you are using to read in the file
clean_text <- as.data.frame(strsplit(text$text, '\\*' ), col.names = "text") %>%
mutate(text = str_replace_all(text, "\n", " "),
text = str_replace_all(text, "- ", ""),
text = str_replace_all(text,"^\\s", "")) %>%
filter(!text == " ") %>%
mutate(paragraphs = ifelse(grepl("^[[:digit:]]", text) == T, text, NA)) %>%
rename(category = text) %>%
mutate(category = ifelse(grepl("^[[:digit:]]", category) == T, NA, category)) %>%
fill(category) %>%
filter(!is.na(paragraphs)) %>%
mutate(paragraphs = strsplit(paragraphs, '^[[:digit:]]{1,3}\\.|\\t\\s[[:digit:]]{1,3}\\.')) %>%
unnest(paragraphs) %>%
mutate(paragraphs = strsplit(paragraphs, 'Download as PDF')) %>%
unnest(paragraphs) %>%
mutate(paragraphs = str_replace_all(paragraphs, "\t", "")) %>%
mutate(paragraphs = ifelse(grepl("javascript", paragraphs), "", paragraphs)) %>%
mutate(paragraphs = str_replace_all(paragraphs, "^\\s ", "")) %>%
filter(!paragraphs == "")
}
測驗您的函式以確保它適用于一個檔案:
extract_info("your_file_name.txt")
## does the result work and look right?
## work on your function until it does
獲取要運行的所有檔案的串列
my_files = list.files()
## by default this will give you all the files in your working directory
## use the `pattern` argument if you only want files that follow
## a certain naming convention
將您的函式應用于這些檔案:
results = lapply(my_files, extract_info)
uj5u.com熱心網友回復:
我沒有使用回圈,而是使用 lapply 并且函式具有與回圈相同的行為:
my_path <- "C:/Users/SAID ABIDI/Desktop/test/"
my_a <- list.files(path = my_path)
my_function <- function(x) {
read_file(paste(my_path, my_a[x], sep = ""))
}
my_var <- lapply(1:length(my_a), my_function)
這對你有幫助嗎?
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/377216.html
下一篇:撰寫一個R回圈來創建新的標準化列
