R 中的文本挖掘 - 从文本文件中删除以关键字开头的行



我正在将文本文件读入R,如下所示:

test<-readLines("D:/AAPL MSFT Earnings Calls/Test/Test.txt")

此文件是从PDF转换而来的,并保留了一些我想删除的标题数据。他们将以"页面"、"市值"等词开头。

如何删除 TXT 文件中以这些关键字开头的所有行?这与删除包含该单词的行相反。


使用下面的答案之一,我修改了一些内容以阅读

setwd("C:/Users/George/Google Drive/PhD/Strategic agility/Source Data/Peripherals Earnings Calls 2016")
text1<-readLines("test.txt")
text
library(purrr)
library(stringr)
text1 <- "foo
Page, bar
baz
Market Cap, qux"
text1 <- readLines(con = textConnection(file))
ignore_patterns <- c("^Page,", "^Market\s+Cap,")
text1 %>% discard(~ any(str_detect(.x, ignore_patterns)))
text1

这是我得到的输出:

> text1
[1] "foo"             "Page, bar"       "baz"             "Market Cap, qux"

foo/baz/qux 字符是什么?谢谢

# once you have read and stored in a data.frame
# perform below subsetting :
x = grepl("^(Page|Market Cap)", df$id) # where df is you data.frame and 'id' is your 
                                       # column name that has those unwanted keywords
df <- df[!x,]  # does the job!

^有助于检查启动。因此,如果行以 Page 或 ( |Market Cap 开头,则grepl返回TRUE

library(purrr)
library(stringr)
file <- "foo
Page, bar
baz
Market Cap, qux"
test <- readLines(con = textConnection(file))
ignore_patterns <- c("^Page,", "^Market\s+Cap,")
test %>% discard(~ any(str_detect(.x, ignore_patterns)))

最新更新