r - 使用 gsub 将弯撇号和引号替换为直撇号和引号
问题描述
我正在尝试使用 gsub 将所有卷曲撇号/引号替换为直引号。当我运行下面的代码时,我遇到了下面屏幕截图中提供的一些问题。
gsub("’","'",prank_df$Prank, ignore.case=TRUE)
gsub("‘","'",prank_df$Prank, ignore.case=TRUE)
gsub('“','"',prank_df$Prank, ignore.case=TRUE)
这是运行上述 gsubs 时的结果:
解决方案
我假设您正在寻找一种灵活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
推荐阅读
- android - 调用 onTrimMemory() 方法时如何重置/重新启动应用程序?
- java - 如何使用 RxJava 1.x 进行 takeUntil 与必须调用具有不同数据的每个页面的分页?
- r - 通过闪亮的 selectInput() 将更改应用于数据表的特定单元格
- javascript - 引导模式未正确关闭
- c# - 不能将 SetVar 与 PostAdd 或 PreAdd 挂钩 PDM Api 一起使用
- c++ - 如何部署 C++ DLL
- sql - 在新列中汇总过去 7 天的销售额
- javascript - JavaScript - 遍历对象并更改嵌套属性
- maven - 为什么 Maven 找不到 ANALYZE-DUPLICATE 函数?
- kotlin - 在 Kotlin 中创建 ByteArray