R的自然排序在部署上有所不同(可能是OS/Locale问题)



我正在使用程序包"自然排序";在此处找到:https://github.com/kos59125/naturalsort据我所知,自然排序在R中的其他地方并没有以良好的方式实现,所以我很高兴找到这个包。

我使用naturalsort函数对文件名进行排序,就像windows资源管理器一样,它在本地工作得很好。

但当我在Google Cloud Run上使用Docker部署的生产环境中使用它时,排序会发生变化。我不知道这是由于区域设置的变化(我是fra Denmark(,还是由于我的windows PC和Docker/Google Cloud Run部署之间的操作系统差异。

我已经创建了一个准备在R:中运行的示例

######## Code start ###########
require(plumber)
require(naturalsort) #for name sorting
#* Retrieve sorted string list
#* @get /sortstrings
#* @param nothing
function(nothing) {

print(nothing)

test <- c("0.jpg", "file (4_5_1).jpeg", "1 tall thin image.jpeg",
"8.jpeg", "8.jpg", "file (2.1.2).jpeg", "file (0).jpeg", "3.jpeg",
"file (1).jpeg", "file (2.1.1).jpeg", "file (0) (3).jpeg", "file (2).jpeg",
"file (2.1).jpeg", "file (4_5).jpeg", "file (4).jpeg", "file (39).jpeg")

print("Direct sort")
print(naturalsort(text = test))

sorted_strings <- naturalsort(text = test)

return(sorted_strings) 
}
######## Code end ###########

我希望它能像下面这样对文件名进行排序,当它直接在脚本中运行时,以及当它通过管道工run API:运行时,它都会在本地进行排序

c("0.jpg", 
"1 tall thin image.jpeg", 
"3.jpeg", 
"8.jpeg", 
"8.jpg", 
"file (0) (3).jpeg", 
"file (0).jpeg", 
"file (1).jpeg", 
"file (2).jpeg", 
"file (2.1).jpeg", 
"file (2.1.1).jpeg", 
"file (2.1.2).jpeg", 
"file (4).jpeg", 
"file (4_5).jpeg", 
"file (4_5_1).jpeg", 
"file (39).jpeg"
)

但相反,它是这样分类的:

c("0.jpg",
"1 tall thin image.jpeg",
"3.jpeg",
"8.jpeg",
"8.jpg",
"file (0) (3).jpeg",
"file (0).jpeg",
"file (1).jpeg",
"file (2.1.1).jpeg",
"file (2.1.2).jpeg",
"file (2.1).jpeg",
"file (2).jpeg",
"file (4_5_1).jpeg",
"file (4_5).jpeg",
"file (4).jpeg",
"file (39).jpeg")

这与windows资源管理器不同。

尝试在naturalsort调用之前修复排序序列。它因区域设置而异,并可能影响字符串的比较(以及排序(方式。

## Get initial value
lcc <- Sys.getlocale("LC_COLLATE")
## Use fixed value
Sys.setlocale("LC_COLLATE", "C")
sorted_strings <- naturalsort(text = test)
## Restore initial value
Sys.setlocale("LC_COLLATE", lcc)

您可以在这里找到?sort?Comparison?locales中的一些详细信息。

最新更新