gpt4 book ai didi

r - 为坐标选择正确的正则表达式

转载 作者:行者123 更新时间:2023-12-04 08:47:37 26 4
gpt4 key购买 nike

我有各种格式的坐标,并尝试获得或多或少通用的转换例程。
为此,我尝试使用正则表达式解析字符串的各个元素,并尝试通过它们在字符串中的出现索引来获取度、分和秒的各个信息。
对某些人来说它有效....但不是对所有人。我非常确信我的问题与我对正则表达式的有限理解密切相关。
因此问题是:谁对正则表达式模式有更好的理解并且可能会有所帮助?
我试图编译一小段代码来演示这个问题。运行下面的示例表明我得到了前四个和最后三个坐标的三个分量。其余的 - 介于两者之间 - 仅提供 2 个组件....

coords = c("-53°30''30.54'",
"s55°30' 30.54",
"55°30'30.54n",
"0°1 0.5S",
"-0°30'30''s",
"S55 30 30",
"-55°30'30''",
"-55° 30' 30''",
"-55° 30' 30",
"-55 sometimes with text rests 30 30''",
"55°30'30,54S",
"S55° 30' 30,54",
"-55° 30' 30.54''"
)

for (i in 1:length (coords)) {
pattern <- gregexpr ("[0-9.]+", coords [i])
print (as.character (unique (unlist (regmatches (coords [i], pattern)))))
}


<Output>
[1] "53" "30" "30.54"
[1] "55" "30" "30.54"
[1] "55" "30" "30.54"
[1] "0" "1" "0.5"
[1] "0" "30"
[1] "55" "30"
[1] "55" "30"
[1] "55" "30"
[1] "55" "30"
[1] "55" "30"
[1] "55" "30" "54"
[1] "55" "30" "54"
[1] "55" "30" "30.54"
下面的正则表达式是一个令人印象深刻的怪物;-)
然而,当坐标采用稍微不同的格式(例如 dec_deg)时,它会出现一些问题。在这种情况下,无法正确识别字符串的第一个或第二个数字。我刚刚用这样的坐标编制了一个列表:
coords = c("-53°30''30.54'",
"s55°30' 30.54",
"55°30'30.54n",
"0°1 0.5S",
"-0°30'30''s",
"S55 30 30",
"-55°30'30''",
"-55° 30' 30''",
"-55° 30' 30",
"-55 有时文本休息 30 30''",
"55°30'30,54S",
"S55° 30' 30,54",
"-55° 30' 30.54''",
"-55.5432 30 30.54",
"-55.30.30",
"55.555",
"55,555S",
"S55,555",
"S55.555",
"55,555°S",
"55.555°",
"-55,555",
“-55.555”
       )

最佳答案

似乎可以与 stringr 一起使用...

library(stringr)
str_extract_all(str_replace_all(coords, ",", "."), "[0-9.\\-]+")

[[1]]
[1] "-53" "30" "30.54"

[[2]]
[1] "55" "30" "30.54"

[[3]]
[1] "55" "30" "30.54"

[[4]]
[1] "0" "1" "0.5"

[[5]]
[1] "-0" "30" "30"

[[6]]
[1] "55" "30" "30"

[[7]]
[1] "-55" "30" "30"

[[8]]
[1] "-55" "30" "30"

[[9]]
[1] "-55" "30" "30"

[[10]]
[1] "-55" "30" "30"

[[11]]
[1] "55" "30" "30.54"

[[12]]
[1] "55" "30" "30.54"

[[13]]
[1] "-55" "30" "30.54"

关于r - 为坐标选择正确的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64228649/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com