【问题标题】:Handling parsed text处理解析的文本
【发布时间】:2017-03-21 02:21:22
【问题描述】:

我想计算解析文本中小于 x 的数字的数量。

这是给我列表的代码:

library(rvest)
library(reshape2)


td <- read_html(x = "http://www.imdb.com/name/nm1287124/?ref_=tt_ov_dr") 
list<- as.list(td %>% # feed `main.page` to the next step%>% # load the page
    html_nodes(".filmo-row") %>% # isloate the text
    html_text())     

有人知道如何计算例如小于 2017 年的数字吗?

(未完成;最终目标是计算某一年之前的导演学分)

【问题讨论】:

  • 请注明您正在使用的所有包。
  • rvest 和 reshape2

标签: r parsing web-scraping imdb


【解决方案1】:

假设我们有:

text <- "asdasd8927askdmasjdo89jans1982736djnaos987anksdjnj2008da"

假设数字总是被[0-9]以外的任何东西包围,那么你可以编写一个函数来执行此操作:

idx <- gregexpr("[0-9]+", text)[[1]]
lens <- attr(idx, "match.length")
nums <- lapply(seq_along(idx), function(i) {
  substr(text, idx[i], idx[i] + lens[i] - 1)
})
nums <- as.numeric(nums)

?grep?substr解释) 最后你可以数出大于 2017 年的数字。

sum(nums > 2017)


编辑(评论)

假设我们只想查看 4 位数字,那么可以调整正则表达式(和 substr 索引)。现在我们搜索“Not a Number” 4 次“a Number”“Not a Number”。因此,为了只提取“数字”部分,我们将substr 晚一个位置开始并提前一个位置停止。

idx <- gregexpr("[^0-9][0-9]{4}[^0-9]", text)[[1]]
lens <- attr(idx, "match.length")
nums <- lapply(seq_along(idx), function(i) {
  substr(text, idx[i] + 1, idx[i] + lens[i] - 2)
})
nums <- as.numeric(nums)

现在nums 仅包含 2 个 4 位数字。

nums
sum(nums > 2017)

【讨论】:

  • 感谢您的回答,但这不适用于我的数据。 (只是为了完整;我想统计某年之前的导演学分,请参阅:imdb.com/name/nm1287124/?ref_=tt_ov_dr
  • 您可以将代码调整为您的特定字符串。如果您只想查看 4 位长的数字,可以使用此正则表达式:[^0-9][0-9]{4}[^0-9]。然后正则表达式搜索模式“NaN 4 乘以数字 NaN”。因此,您必须在 substr 函数 +1 和 -1 中调整开始和停止索引:substr(text, idx[i] + 1, idx[i] + lens[i] - 2)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-12
  • 2013-01-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多