gpt4 book ai didi

parsing - 在 Golang 中解析格式化字符串

转载 作者:IT王子 更新时间:2023-10-29 01:55:41 27 4
gpt4 key购买 nike

我正在尝试使用 Golang 解析 GNSS RINEX 文件。

例如,这里是 VERSION 行的 RINEX 规范:

+--------------------+------------------------------------------+------------+
|RINEX VERSION / TYPE| - Format version (2.11) | F9.2,11X, |
| | - File type ('O' for Observation Data) | A1,19X, |
| | - Satellite System: blank or 'G': GPS | A1,19X |
| | 'R': GLONASS | |
| | 'S': Geostationary | |
| | signal payload | |
| | 'E': Galileo | |
| | 'M': Mixed | |
+--------------------+------------------------------------------+------------+

RINEX 文件中的每一行的宽度固定为 80 个 ASCII 字符 + "\n"。在此示例中,前 9 个字符表示版本号( float )。

在 Python 中我可能会使用:

struct.unpack("9s11s1s19s1s19s20s", line)

这将返回一个包含 7 个字符串的元组。

我是新手,一直在尝试使用 fmt.Sscanf 来阅读格式化文本:

func main() {
str := " 2.11 OBSERVATION DATA G (GPS) RINEX VERSION / TYPE\n"
var value float32
a, err := fmt.Sscanf(str,"%9.2f", &value)
fmt.Println(a)
fmt.Println(err)
fmt.Println(value)
}

返回:

0
bad verb %. for float32
0

go中有没有包可以解析固定宽度的数据?

如果不是,编写类似于 Python 结构的东西的好方法可能是什么?

最佳答案

例如,

package main

import (
"errors"
"fmt"
"strconv"
"strings"
)

// http://gage14.upc.es/gLAB/HTML/LaunchHTML.html
// http://gage14.upc.es/gLAB/HTML/Observation_Rinex_v2.11.html

func parseVersionType(line string) (version float64, fileType, satellite, label string, err error) {
label = line[60:80]
if label != "RINEX VERSION / TYPE" {
err = errors.New("Unknown header label")
return
}
version, err = strconv.ParseFloat(strings.TrimSpace(line[0:9]), 64)
if err != nil {
return
}
fileType = line[20:21]
satellite = line[40:41]
return
}

func main() {
line := " 2.11 OBSERVATION DATA G (GPS) RINEX VERSION / TYPE\n"
version, fileType, satellite, label, err := parseVersionType(line)
fmt.Printf("%g %q %q %q %v\n", version, fileType, satellite, label, err)
}

输出:

2.11 "O" "G" "RINEX VERSION / TYPE" <nil>

关于parsing - 在 Golang 中解析格式化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25070312/

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