R挣扎。我正在使用以下内容从文本中提取引用,在大型数据集上有多个结果。我试图使输出为数据帧内的字符串,因此我可以轻松地将其作为csv与他人共享。
样本数据:
normalCase <- 'He said, "I am a test," very quickly.'
endCase <- 'This is a long quote, which we said, "Would never happen."'
shortCase <- 'A "quote" yo';
beginningCase <- '"I said this," he said quickly';
multipleCase <- 'When asked, "No," said Sam "I do not like green eggs and ham."'
testdata = c(normalCase,endCase,shortCase,beginningCase,multipleCase)
使用以下内容提取引号和字符缓冲区:
result <-function(testdata) {
str_extract_all(testdata, '[^\"]?{15}"[^\"]+"[^\"]?{15}')
}
extract <- sapply(testdata, FUN=result)
摘录是矩阵中的列表。但是,我希望提取的内容是一个字符串,以后我可以将其合并为一个数据列。我该如何转换呢?
normalCase <- 'He said, "I am a test," very quickly.'
endCase <- 'This is a long quote, which we said, "Would never happen."'
shortCase <- 'A "quote" yo';
beginningCase <- '"I said this," he said quickly';
multipleCase <- 'When asked, "No," said Sam "I do not like green eggs and ham."'
testdata = c(normalCase,endCase,shortCase,beginningCase,multipleCase)
# extract quotations
gsub(pattern = "[^\"]*((?:\"[^\"]*\")|$)", replacement = "\\1 ", x = testdata)
[1] "\"I am a test,\" "
[2] "\"Would never happen.\" "
[3] "\"quote\" "
[4] "\"I said this,\" "
[5] "\"No,\" \"I do not like green eggs and ham.\" "
pattern = "[^\"]"
将与除双引号之外的任何字符匹配pattern = "[^\"]*"
除双引号0或多次外,将与任何字符匹配pattern = "\"[^\"]*\""
将与双引号匹配,然后除双引号之外的任何字符0次或更多次,再与另一个双引号(即)匹配pattern = "(?:\"[^\"]*\")"
将与报价匹配,但不会捕获它pattern = "((?:\"[^\"]*\")|$)"
将与引号或endOfString匹配,并捕获它。请注意,这是我们捕获的第一组replacement = "\\1 "
将替换为我们捕获的第一组,后跟一个空格本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句