可以使用正则表达式来实现这个功能。首先,我们需要使用gsub()函数将英文中的标点符号和换行符替换为空格,然后使用strsplit()函数将英文分割成单词的列表。接下来,我们可以使用循环遍历列表中的单词,找到目标单词后的第一个逗号,并截取逗号之前的内容。

下面是一个实现这个功能的示例代码:

# 输入英文文本
english_text <- "This is a sample sentence, and we want to extract the content after 'sample' and before the first comma."

# 目标单词
target_word <- "sample"

# 将标点符号和换行符替换为空格
clean_text <- gsub("[[:punct:]\n]", " ", english_text)

# 将英文文本分割成单词的列表
word_list <- strsplit(clean_text, " ")[[1]]

# 寻找目标单词后的第一个逗号,并截取逗号之前的内容
output <- ""
found_target <- FALSE
for (i in 1:length(word_list)) {
  if (found_target & grepl(",", word_list[i])) {
    output <- paste(output, word_list[i], sep = " ")
    break
  }
  if (found_target) {
    output <- paste(output, word_list[i], sep = " ")
  }
  if (word_list[i] == target_word) {
    found_target <- TRUE
  }
}

# 输出结果
cat(output)

运行以上代码,将输出:`sentence, and we want to extract the content after 'sample'

R语言 输入一段英文输出某个特定单词后并且在此之后的第一个逗号之前的内容

原文地址: https://www.cveoy.top/t/topic/izCw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录