首页 > 解决方案 > 使用 gsub 将弯撇号和引号替换为直撇号和引号

问题描述

我正在尝试使用 gsub 将所有卷曲撇号/引号替换为直引号。当我运行下面的代码时,我遇到了下面屏幕截图中提供的一些问题。

gsub("’","'",prank_df$Prank, ignore.case=TRUE) gsub("‘","'",prank_df$Prank, ignore.case=TRUE) gsub('“','"',prank_df$Prank, ignore.case=TRUE)

这是尝试上述功能之前的输出: 在此处输入图像描述

这是运行上述 gsubs 时的结果:

在此处输入图像描述

标签: rgsub

解决方案


我假设您正在寻找一种灵活gsub表达方式的方法。您可以查看qdap::mgsub允许检查矢量化模式、替换和字符对象的功能。我可以给你一个愚蠢的例子:

str <- "This string ‘has’ non “standard“ elements"

df = data.frame(str = rep(str,5))

qdap::mgsub(pattern = c("‘", "’", '“'),
      replacement = c("'","'",'"'),
      df$str)
[1] "This string 'has' non \"standard\" elements" "This string 'has' non \"standard\" elements"
[3] "This string 'has' non \"standard\" elements" "This string 'has' non \"standard\" elements"
[5] "This string 'has' non \"standard\" elements"

顺便说一句,如果您想"在字符串中使用大引号 ( ),请将R它们分隔开。使用打印功能时,例如cat,您将看到预期的输出:

cat(qdap::mgsub(pattern = c("‘", "’", '“'),
+             replacement = c("'","'",'"'),
+             df$str), sep = "\n")
This string 'has' non "standard" elements
This string 'has' non "standard" elements
This string 'has' non "standard" elements
This string 'has' non "standard" elements
This string 'has' non "standard" elements

推荐阅读