尝试使用R中的正则表达式将在线表单中的问题与答案分开
我正在将表格读入R中的数据框中。其中一列包含表格的内容,包括问题和答案。我试图把这两个问题分开,而不是把每一个不同形式的问题都组合起来。数据的结构如下所示尝试使用R中的正则表达式将在线表单中的问题与答案分开,r,R,我正在将表格读入R中的数据框中。其中一列包含表格的内容,包括问题和答案。我试图把这两个问题分开,而不是把每一个不同形式的问题都组合起来。数据的结构如下所示 text <- c('Select the benefit your question is related to: Life or AD&D Insurance\r\n What is your question?: I am interested in purchasing additional life insurance
text <- c('Select the benefit your question is related to: Life or AD&D Insurance\r\n What is your question?: I am interested in purchasing additional life insurance and was wondering if someone could assist me with locating my most recent Life Insurance Statement.\r\n')
number <- c(1)
df <- data.frame(number,text)
所以每个问题都从一行开始,以冒号结束
因此,我想以问题列表和相应答案列表作为结束。首先,将文本分成几行。然后,一个简单的正则表达式允许您提取问题和答案
Lines = unlist(strsplit(text, "\r\n"))
Questions = sub("(.*?):.*", "\\1", Lines)
Answers = sub(".*?:(.*)", "\\1", Lines)
Questions
[1] "Select the benefit your question is related to"
[2] " What is your question?"
Answers
[1] " Life or AD&D Insurance"
[2] " I am interested in purchasing additional life insurance and was wondering if someone could assist me with locating my most recent Life Insurance Statement."
最快的方法是使用gsub,有效的代码是:
df<-data.frame(question=gsub("[?][:].*","?",text), answer=gsub(".*[?:]","",text),id=1)
问题是:
df$question
[1] Select the benefit your question is related to: Life or AD&D Insurance\r\n What is your question?
使用stringr::str_match_all:
伟大的这起作用了。有两个问题有两个对应的答案。这几乎奏效了,但第一个问题的结尾是:不是?:所以第一个答案被挤在两个问题之间。可能可以修改模式以获得这两个问题。这非常有效。我有数千个问题,每组问题都与df$id中的唯一标识符存储相关联。如何将此标识符添加到结果中,以便检索与特定id关联的所有问题?@user3482393检查更新的答案。有几件事。这在大多数情况下都有效,但有些失败了。如果所有项目都有两个或两个以上的问题,它就可以工作。但有些项目只有一个问题和一个答案。因此,当我们试图将列表转换为数据帧时,它失败了。您还可以解释正则表达式语句“\\s**?:\\s**?\r\n”以及lapply中functionx x[,-1]的函数。谢谢
df$question
[1] Select the benefit your question is related to: Life or AD&D Insurance\r\n What is your question?
tmp <- lapply(stringr::str_match_all(df$text, '\\s*(.*?):\\s*(.*?)\r\n'),
function(x) x[, -1])
result <- cbind(id = rep(df$number, sapply(tmp, nrow)),
do.call(rbind.data.frame, tmp))
names(result) <- c('question', 'answer')
result