【问题标题】:Text Mining in R - Remove Rows from Text File Starting With KeywordsR中的文本挖掘-从以关键字开头的文本文件中删除行
【发布时间】:2017-01-10 18:03:13
【问题描述】:

我正在将一个文本文件读入 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 字符?谢谢你

【问题讨论】:

  • grepl("^(Page|Market Cap)", df$id) 用于对行进行子集化。替换为您的关键字。和id 与您的第一列

标签: r pdf text-mining


【解决方案1】:
# 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

【讨论】:

  • 您好,抱歉耽搁了。您能否向我推荐一个可以帮助我将文本文件转换为数据框的资源?文本文件将是非结构化的通话记录。这看起来是一个很好的解决方案,但我是一个 R 菜鸟,我需要补习!谢谢。
  • 使用 read.table 获取详细信息,在 R 控制台中键入 ?read.table。 @GeorgeM
  • 嘿@GeorgeM 希望你用真实数据做对了!
  • 我做到了。一直往前走。感谢您的帮助。
【解决方案2】:
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)))

【讨论】:

  • 我认为我做错了什么。我的代码/输出粘贴在顶部。理想情况下,当我打印结果时,我基本上应该看到我的文本文件被删除了包含页面和市值的行是否正确?感谢您的耐心等待,我是新手(显然)。
  • 您是否先安装了purrrstringrinstall.packages(c("purrr", "stringr")) 而没有错误? (检查install.packages(...的输出
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-02
  • 2012-01-25
  • 1970-01-01
  • 1970-01-01
  • 2013-04-29
  • 1970-01-01
相关资源
最近更新 更多