r - 使用 R 进行特征提取
问题描述
我的问题是关于特征提取的。
我想从我的文本中构建一个数据框。
我的数据是:
text <- c("#*TeX: The Program",
"#@Donald E. Knuth",
"#t1986",
"#c",
"#index68",
"",
"#*Foundations of Databases.",
"#@Serge Abiteboul,Richard Hull,Victor Vianu",
"#t1995",
"#c",
"#index69",
"#%1118192",
"#%189",
"#%1088975",
"#%971271",
"#%832272",
"#!From the Book: This book will teach you how to write specifications of computer systems, using the language TLA+.")
我的预期输出是:
expected <- data.frame(title=c("#*TeX: The Program", "#*Foundations of Databases."), authors=c("#@Donald E. Knuth", "#@Serge Abiteboul,Richard Hull,Victor Vianu"), year=c("#t1986", "#t1995"), revue=c("#c", "#c"), id_paper=c("#index68", "#index69"),
id_ref=c(NA,"#%1118192, #%189, #%1088975, #%971271, #%832272"), abstract=c(NA, "#!From the Book: This book will teach you how to write specifications of computer systems, using the language TLA+."))
提前感谢您的回答或任何其他建议。
解决方案
我想我认识到这种模式,尽管您可能需要更清楚地了解我的一两个假设。(我认为您读取数据的方法可能会阻止对这些假设的需要,但我不确定。)
首先,我将制作模式到列名的正则表达式“映射”:
patterns <- c(title = "^#\\*", author = "^#@",
year = "^#t", revue = "^#c",
id_paper = "^#index", abstract = "^#%",
mismatch = "^([^#]|#[^*@%tci])")
现在,假设标题始终是其他字段序列中的第一个,我将向量拆分为每个标题向量的列表:
titles <- split(text, cumsum(grepl("^#\\*", text)))
str(titles)
# List of 2
# $ 1: chr [1:6] "#*TeX: The Program" "#@Donald E. Knuth" "#t1986" "#c" ...
# $ 2: chr [1:11] "#*Foundations of Databases." "#@Serge Abiteboul,Richard Hull,Victor Vianu" "#t1995" "#c" ...
现在是一个快速的辅助功能:
standardize_title <- function(x) {
o <- lapply(patterns, function(ptn) paste(x[grepl(ptn, x)], collapse = ", "))
o[nchar(o) == 0] <- NA_character_
o
}
现在将该函数应用于每个标题titles
:
do.call(rbind.data.frame, c(stringsAsFactors=FALSE, lapply(titles, standardize_title)))
# title author year revue id_paper abstract mismatch
# 1 #*TeX: The Program #@Donald E. Knuth #t1986 #c #index68 <NA> <NA>
# 2 #*Foundations of Databases. #@Serge Abiteboul,Richard Hull,Victor Vianu #t1995 #c #index69 #%1118192, #%189, #%1088975, #%971271, #%832272 #!From the Book: This book will teach you how to write specifications of computer systems, using the language TLA+.
(也可以使用dplyr::bind_rows
或data.table::rbindlist
代替do.call(rbind.data.frame, ...)
。)
最大的假设是标题总是模式中的第一个。如果这不是真的,那么您将得到不正确的结果,尽管不会出现这样的警告或错误。
推荐阅读
- swift - 如何在 SwiftUI 中的特定时间循环播放背景音乐
- python - 我需要什么范围和权限才能让别人从我的 Google 云端硬盘下载文件?
- python - 使用索引列表拆分列表
- python - 使用 xlrd 引擎在 xls 文件上调用 pands read_excel 时出现 AssertionError
- javascript - 时刻不计算天数正确,还是我错了?(我是但为什么)
- r - 对具有多列的两个数据框列表执行多个两个样本 t 检验
- microsoft-graph-api - 状态码:禁止;原因:该请求未对此用户或应用程序授权
- javascript - 通过内部值检测 TD 元素并将其移动到最后
- javascript - 获取人的确切年龄,取决于月份和日期,而不仅仅是年份
- amazon-web-services - Selenium 在远程服务器(AWS EC2)上无法正常工作