r - 从民主辩论中划定文本
问题描述
我正在尝试按名字、时间戳和文本来分隔以下数据。目前,整个数据列在 1 列中作为数据框,该列称为 Text 1。这是它的外观
text
First Name: 00:03 Welcome Back text text text
First Name 2: 00:54 Text Text Text
First Name 3: 01:24 Text Text Text
这是我到目前为止所做的:
text$specificname = str_split_fixed(text$text, ":", 2)
它创建了以下内容
text specific name
First Name: 00:03 Welcome Back text text text First Name
First Name 2: 00:54 Text Text Text First Name2
First Name 3: 01:24 Text Text Text First Name 3
如何对时间戳和文本执行相同操作?这是最好的方法吗?
编辑 1:这就是我引入数据的方式
#Specifying the url for desired website to be scraped
url = 'https://www.rev.com/blog/transcript-of-july-democratic-debate-night-1-full-transcript-july-30-2019'
#Reading the HTML code from the website
wp = read_html(url)
#assignging the class to an object
alltext = html_nodes(wp, 'p')
#turn data into text, then dataframe
alltext = html_text(alltext)
text = data.frame(alltext)
解决方案
假设text
是最后注中所示的形式,即每行一个分量的字符向量,我们可以使用read.table
read.table(text = gsub(" +", ",", text), sep = ",", as.is = TRUE)
给出这个data.frame:
V1 V2 V3
1 First Name: 00:03 Welcome Back text text text
2 First Name 2: 00:54 Text Text Text
3 First Name 3: 01:24 Text Text Text
笔记
Lines <- "First Name: 00:03 Welcome Back text text text
First Name 2: 00:54 Text Text Text
First Name 3: 01:24 Text Text Text"
text <- readLines(textConnection(Lines))
更新
pat
关于添加到问题中的 EDIT,定义一个匹配可能的空格、2 位数字、冒号、2 位数字和可能更多空格的正则表达式。然后grep
取出与它匹配的所有行,tt
并在左边的每一行中将匹配替换为 @、模式(除了空格)和 @giving g
。最后使用 @ 作为字段分隔符来阅读它DF
。
pat <- "\\s*(\\d\\d:\\d\\d)\\s*"
tt <- grep(pat, text$alltext, value = TRUE)
g <- sub(pat, "@\\1@", tt)
DF <- read.table(text = g, sep = "@", quote = "", as.is = TRUE)
推荐阅读
- django - 我对 app.py 中使用的 ready 函数感到困惑
- airflow - 气流 - 在重试中保留状态
- ffmpeg - 如何使用 ffMpeg 缓存 AVI 文件
- yii2 - 在 Yii2 中使用 DBquery 从选择查询中添加值
- sorting - 当比较函数对某些对返回“不知道”时进行排序
- airflow - Airflow SSHOperator 不会 source linux 环境
- reactjs - 如何使用 webpack 分别捆绑供应商和主脚本?
- mysql - 获取 mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'vsearch'@'localhost' (using password: YES) with python
- javascript - JS数组合并求和
- javascript - 有没有一种方便的方法来引用 Svelte 组件中的 DOM 元素?