[英]Natural sorting with R differs on deployment (maybe OS/Locale issue)
I am using the package "naturalsort" found here: https://github.com/kos59125/naturalsort Natural sorting is not something that is implemented elsewhere in a good manner in R as far as I know, so I was happy to find this package。
我使用 function naturalsort 對文件名進行排序,就像 windows explorer 一樣,它在本地工作得很好。
但是,當我在使用 Google Cloud Run 上的 Docker 部署的生產環境中使用它時,排序會發生變化。 我不知道這是由於語言環境的變化(我來自丹麥)還是由於我的 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
中找到一些詳細信息,等等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.