r - Pig Latin Converter - 需要帮助找出如何查找而不是转换数字元素
问题描述
我正在编写一个将短语转换为猪拉丁语的函数。但是,如果该短语包含一个数字,则该函数需要将它们保持原样,并且我在寻找一种方法时遇到了一些问题。
我尝试过使用regmatch
,gsub
和which
语句,但还没有找到最好的方法。
以下是我尝试过的一些事情:
phrase <- "the 24 brown fox jumps over the lazy brown dog"
这是功能:
piglatin = function(phrase) {
phrase2 <- tolower(phrase)
phrase3 <- strsplit(phrase2, split=" ")[[1]]
phrase4 <- paste(gsub("(.)(.*)", "\\2\\1ay", phrase3), collapse=" ")
return(phrase4)
}
这是我提取数字的尝试。这需要在某处插入到函数中。
matches <- regmatches(phrase, gregexpr("[[:digit:]]+", phrase))
as.numeric(unlist(matches))
x <- gregexpr("[0-9]+", phrase) # Numbers with any number of digits
x2 <- as.numeric(unlist(regmatches(phrase, x)))
输入:
"the 24 brown fox jumps over the lazy brown dog"
实际输出:
"hetay 42ay rownbay oxfay umpsjay veroay hetay azylay rownbay ogday"
期望的输出:
"hetay 24 rownbay oxfay umpsjay veroay hetay azylay rownbay ogday"
解决方案
与其尝试捕获数字,不如使用几个捕获组可能更容易 - 第一个用于第一个字母,第二个用于后续字母(如果存在),第三个用于后续空白(如果存在)。
gsub("([a-zA-Z])([a-zA-Z]*)(\\s?)", "\\2\\1ay\\3", phrase)
#[1] "hetay 24 rownbay oxfay umpsjay veroay hetay azylay rownbay ogday"
推荐阅读
- android - Android MediPlayer prepareAsync() java.lang.IllegalStateException
- javascript - SQL 滞后与 jquery 变量
- javascript - VUEJS - 将我的方法的返回绑定到我的子模板
- javascript - 从当前帖子自定义字段中提取简码并在 Wordpress 中执行
- swiftui - 如何直接从 SwiftUI 中的 Widget 打开 Safari?
- java - 如何有效地使用 CompletableFuture 映射每个输入的异步任务
- spring-boot - Spring Boot + Thymeleaf:组合过滤和分页列表
- mysql - 如何修复 InnoDB 损坏的数据结构?
- android - 当数据按模型类在回收站视图中获取 firebase 数据库时,错误应用程序崩溃
- c# - C#/Unity Time.deltaTime 使相机跟随跳跃