R 如何随机发布文本

R 如何随机发布文本,r,R,我正在尝试创建一些文本。我有一个如下的数据框(其中包含更多的文本行) 如何将随机替换的思想引入到gsub或str_replace?我们可以得到一个样本,该样本具有替换的可能值,然后进行替换 v1 <- sample(c("and", "It"), nrow(out), replace = TRUE) gsub("\\.\\s*(?=[a-z])", " ", str_replace_all(out[,1], "(?i)It", v1), perl = TRUE) #[1] "The roa

我正在尝试创建一些文本。我有一个如下的数据框(其中包含更多的文本行)


如何将随机替换的思想引入到
gsub
str_replace

我们可以得到一个
样本
,该样本具有替换的可能值,然后进行替换

v1 <- sample(c("and", "It"), nrow(out), replace = TRUE)
gsub("\\.\\s*(?=[a-z])", " ", str_replace_all(out[,1], "(?i)It", v1), perl = TRUE)
#[1] "The road and long and has many a winding path"
#[2] "The rain clouds are coming"                         
#[3] "My aunt has blue hair. It is like Marj Simpson's hair" 
#[4] "The oesophagus is long and is like a toothpaste tube" 

v1为什么要这样做?请注意,您所做的不仅仅是用
替换
,您还替换了一些标点符号(可能)。@TimBiegeleisen我正在为一个项目创建文本报告,该项目由单独的句子组成。我想介绍报告之间的变化,所以随机添加连词是许多方法之一…问题已经更新,以反映摆脱了句号也好,这很聪明,谢谢@akrun。换句话说,你创建一个随机“It”和“and”的列表,然后找到并替换整个数据帧,这样用自身替换就不会产生替换,给人以随机替换的印象。@SebastianZeki谢谢,是的,您可以执行
示例
,使用
str_replace
它将遍历替换列表中的每个单独元素,并执行此操作以替换列中的相应元素
The road it long and has many a winding path
The rain clouds are coming
My aunt has blue hair. It is like Marj Simpson's hair
The oesophagus is long and is like a toothpaste tube
v1 <- sample(c("and", "It"), nrow(out), replace = TRUE)
gsub("\\.\\s*(?=[a-z])", " ", str_replace_all(out[,1], "(?i)It", v1), perl = TRUE)
#[1] "The road and long and has many a winding path"
#[2] "The rain clouds are coming"                         
#[3] "My aunt has blue hair. It is like Marj Simpson's hair" 
#[4] "The oesophagus is long and is like a toothpaste tube"