首页 > 解决方案 > 从民主辩论中划定文本

问题描述

我正在尝试按名字、时间戳和文本来分隔以下数据。目前,整个数据列在 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)

标签: r

解决方案


假设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)

推荐阅读