繁体   English   中英

如何从非结构化文本中提取某些项目?

[英]How do I extract certain items from unstructured text?

我在 R 中有一个非常非结构化的数据框 (df),其中包括一个文本列。

df$text 的示例如下所示

John Smith 3.8 GPA johnsmith@gmail.com, https://link.com

我正在尝试从字段中提取 GPA 并保存到名为 df$GPA 的新列中,但无法使其正常工作。

我努力了:

df$gpa <- sub('[0-9].[0-9] GPA',"\\1", df$text)

但这会返回整个文本块。

我也在尝试提取 url 但我也不确定如何做到这一点。有人有什么建议吗?

这是在(?=GPA)中使用正前瞻和str_extract中的stringr的解决方案:

df$GPA <- str_extract(df$text, "\\d+\\.\\d+\\s(?=GPA)")

具有反向引用的sub解决方案是:

df$GPA <- sub(".*(\\d+\\.\\d+).*", "\\1", df$text)

结果:

df
                                                      text GPA
1 John Smith 3.8 GPA johnsmith@gmail.com, https://link.com 3.8

数据:

df <- data.frame(text = "John Smith 3.8 GPA johnsmith@gmail.com, https://link.com")

我们可以使用正则表达式环视来提取数字部分

library(stringr)
df$GPA <- str_extract(df$text, "[0-9.]+(?=\\s*GPA)")
df$GPA
#[1] "3.8"

或者在带有regmatches/regexprbase R

regmatches(df$text, regexpr("[0-9.]+(?=\\s*GPA)", df$text, perl = TRUE))

数据

df <- data.frame(text = 'John Smith 3.8 GPA johnsmith@gmail.com, https://link.com', stringsAsFactors = FALSE)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM