在Go中从文件解析矩阵

huangapple go评论73阅读模式
英文:

Parsing a Matrix from a File in Go

问题

我有一个包含以下内容的文件:

 1  2  3  4  5
 6  0  0  0  7
 8  0  0  0  9
10  0  0  0 11
12 13 14 15 16

我想要的是一个[][]int的多维数组(或切片)。我尝试使用scanner.Scanner库进行操作:

scan.Init(f) // f是一个文件
scan.Whitespace = 1<<'\t' | 1<<'\r' | 1<<' '
tok := scan.Scan()
for tok != scanner.EOF {
    // 对tok进行处理
    if tok == scanner.String {
        fmt.Print("\n")
    } else if tok == scanner.Int {
        // 处理整数值
        // 我如何获取匹配的token值?
    }        
    
    tok = scan.Scan()
}

我找不到获取匹配的token值的方法。

所以有两个问题:

  1. 如何获取任何扫描到的token的值?
  2. 在不知道确切大小的情况下,如何动态创建这个二维切片/数组?(可以是任意大小)
英文:

I'm having a file with the following contents:

 1  2  3  4  5
 6  0  0  0  7
 8  0  0  0  9
10  0  0  0 11
12 13 14 15 16

What I want is an multidimensional array (or slice) of [][]int. I tried to fiddle around with the scanner.Scanner library:

scan.Init(f) // f is a file
scan.Whitespace = 1<<'\t' | 1<<'\r' | 1<<' '
tok := scan.Scan()
for tok != scanner.EOF {
	// do something with tok
	if tok == scanner.String {
		fmt.Print("\n")
	} else if tok == scanner.Int {
		// Handle int value
		// How do I get the matched token value?
	}		
	
	tok = scan.Scan()
}

I can't find a way to get the value of the token that was matched.

So two questions:

  1. How do I get the value of any scanned token?
  2. How can I dynamically create that two-dimensional slice/array before knowing it's exact size? (can be any size really)

答案1

得分: 2

Ad 1: Scanner.TokenText

Ad 2.: 简而言之 - 如果维度需要从文本表示中推断出来,内循环:将行片段(比如 []int)追加到一行中,直到遇到换行符 -> 最大列数。外循环:将这些行片段(追加到一个 [][]int)直到遇到文件结束符 -> 最大行数。

英文:

Ad 1: Scanner.TokenText

Ad 2.: Briefly - if the dims are to be inferred from the text representation, inner cycle: Append to a line slice (say []int) until line break -> num of mx cols. Outer cycle: Append those line slices (to a [][]int) until EOF -> num of mx rows.

答案2

得分: 1

我不会使用scanner包(适用于解析上下文无关文法,类似于Go语言)来读取文件中的数字这样简单的任务。我会使用以下方法之一:

  • 一个简单的循环和fmt.Fscan,或者
  • ioutil.ReadFile,strings.Split和strconv.Atoi

在不知道确切大小之前,我如何动态创建二维切片/数组?(可以是任意大小)

你不能。要么在第二次读取文件时知道确切的大小,要么只需使用append来动态调整切片的底层数组大小。多次调用append()也会导致摊销的O(n)行为,所以这不应该是个问题。

英文:

I wouldn't use the scanner package (which is suited to parse context free grammars, similar to the Go language) for such a simple task of reading numbers from a file. I would either use:

> How can I dynamically create that two-dimensional slice/array before knowing it's exact size? (can be any size really)

You can't. Either read the file twice to know the exact size on your 2nd pass, or just use append to dynamically resize the underlying array of the slice. Calling append() multiple times also results in an amortized O(n) behavior, so that shouldn't be a problem.

huangapple
  • 本文由 发表于 2011年11月24日 21:25:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/8257797.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定