您可以将文件视为 html 并像在抓取它一样探索它rvest
:
library(rvest)
library(stringr)
# Extract the html from the file
html = read_html('~/Downloads/0000897101-04-000425.txt')
# Get all the 'p' nodes (you can do the same for 'table')
p_nodes <- html %>% html_nodes('p')
# Get the text from each node
p_nodes_text <- p_nodes %>% html_text()
# Find the nodes that have the term you are looking for
match_indeces <- str_detect(p_nodes_text, fixed('discount rate', ignore_case = TRUE))
# Keep only the nodes with matches
# Notice that I remove the first match because rvest adds a
# 'p' node to the whole file, since it is a text file
match_p_nodes <- p_nodes[match_indeces][-1]
# If you want to see the results, you can print them like this
# (or you could send them to a file)
for(i in 1:length(match_p_nodes)) {
cat(paste0('Node #', i, ': ', as.character(match_p_nodes[i]), '\n\n'))
}
对于<table>
标签,您不会删除第一个匹配项:
table_nodes <- html %>% html_nodes('table')
table_nodes_text <- table_nodes %>% html_text()
match_indeces_table <- str_detect(table_nodes_text, fixed('discount rate', ignore_case = TRUE))
match_table_nodes <- table_nodes[match_indeces_table]
for(i in 1:length(match_table_nodes)) {
cat(paste0('Node #', i, ': ', as.character(match_table_nodes[i]), '\n\n'))
}