r - 如何从非结构化文本中提取某些项目?
问题描述
我在 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)
但这会返回整个文本块。
我也在尝试提取网址,但我也不确定该怎么做。有人有什么建议吗?
解决方案
(?=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")
推荐阅读
- python - 使用 save_model 保存当前用户
- zfs - 接收克隆和覆盖源的增量 ZFS 流
- tfs - 我们能否将 TFS 2015 更新 2 集合迁移到 TFS 2017 更新 3.1
- c++ - 在 Visual Studio 2015 中重用 cmake 构建的 QT 项目:“connectSlotsByName:无匹配信号”
- python - 如何从 tkinter python 中的 csv 文件中删除选定的列表行?
- ubuntu - systemd 错误“无法启动服务:未正确加载单元服务:执行格式错误”
- python - 将 CSV 解析为 Pytorch 张量
- c++ - 'cin' 内循环:读取错误
- angular - angular4的订阅块中的属性值没有改变
- linux - 防止 usbhid 认领设备