小编ale*_*rab的帖子

R中的快速字符串匹配

我试图在大型数据集中进行单词匹配.我想知道是否有办法加快我工作流程中最慢的操作.

我的目的是找到单词词典和单词向量列表之间匹配的位置.

words <- c("cat", "dog", "snake", "cow")
scores <- c(1.5, 0.7, 3.5, 4.6)
dic <- data.frame(words, scores)

wordList <- list(c("jiraffe", "dog"), c("cat", "elephant"), c("snake", "cow"))
Run Code Online (Sandbox Code Playgroud)

到目前为止我发现的最快的方法是这样做:

matches <- function(wordList) {
    subD <- which(dic$words %in% wordList)
}
Run Code Online (Sandbox Code Playgroud)

我想要的输出是:

matches(wordList):
list(c(2), c(1), c(3, 4))
Run Code Online (Sandbox Code Playgroud)

我可以稍后用它来获得每个wordList单元的平均分数

averageScore <- sapply(matches, function(x) {mean(dic[x, "scores"]})
Run Code Online (Sandbox Code Playgroud)

有没有比我在函数中做的更快的方式进行字符串匹配:

subD <- which(dic$words %in% wordList)
Run Code Online (Sandbox Code Playgroud)

我尝试了dplyr方式,认为它可能更快,使用第一个"过滤器"来获取"dic"的子集并在其上应用"colMeans",但它似乎是两倍慢.

此外,在循环中运行我的匹配函数与在其上使用"lapply"一样慢.

我错过了什么吗?有没有比两者都快的方法?

string r

8
推荐指数
1
解决办法
649
查看次数

在macthon中将mac路径转换为posix

我试图在Mac中将Mac路径转换为POSIX路径.我想转换这样的东西:

'Main HD:Users:sasha:Documents:SomeText.txt'
Run Code Online (Sandbox Code Playgroud)

对此:

'/Users/sasha/Documents/SomeText.txt'
Run Code Online (Sandbox Code Playgroud)

我知道我可以简单地将字符串拆分成一个列表,然后使用正确的分隔符重新加入它.但我相信必须有一个更加优雅的解决方案,我可能会涉及"macpath"或"os.path"python模块.但是,我无法弄清楚这些模块中的功能是否可以在两种格式之间进行转换.

简单的字符串操作解决方案的另一个问题是,如果我有多个HD,那么一个简单的解决方案将无法工作.例如:

如果你有一条路径:

'Extra HD:SomeFolder:SomeOtherText.txt'
Run Code Online (Sandbox Code Playgroud)

我们希望将其转换为:

'/Volumes/Extra HD/SomeFolder/SomeOtherText.txt'
Run Code Online (Sandbox Code Playgroud)

不是:

'/SomeFolder/SomeOtherText.txt'
Run Code Online (Sandbox Code Playgroud)

python macos path

5
推荐指数
1
解决办法
583
查看次数

标签 统计

macos ×1

path ×1

python ×1

r ×1

string ×1