Reading strings, integers and doubles from file with GoLang

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

Reading strings, integers and doubles from file with GoLang

问题

在Google Go中,你可以使用bufio.Scanner来从文件中读取数据。对于你的数据文件,你可以按照以下步骤进行读取和分割变量:

  1. 打开文件:

    file, err := os.Open("filename.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()
    
  2. 创建一个bufio.Scanner对象来读取文件:

    scanner := bufio.NewScanner(file)
    
  3. 使用scanner.Scan()循环读取文件的每一行:

    for scanner.Scan() {
        line := scanner.Text()
        // 在这里对每一行进行处理
    }
    
  4. 在每一行中,使用strings.Fields()函数将字符串分割成多个字段:

    fields := strings.Fields(line)
    // fields[0] 是字符串
    // fields[1] 是浮点数
    // fields[2] 是整数
    

这样,你就可以将每一行的数据分割成不同的变量了。请根据你的需求进行进一步的处理和使用这些变量。

英文:

How to read data from file in Google Go when my data file looks like this:

SomeString      200.0   2
OtherString     100.6   9
OneMoreString   550.8   1

(String, double and integer). I tried bufio.readLine and bufio.readString but these are reading whole line, while i need seperated variables.

答案1

得分: 4

以下是翻译好的内容:

这样的代码可能有效如果你的字符串中有空格你可能需要以不同的方式处理

package main

import (
  "fmt"
  "os"
)

func main() {
   f, err := os.Open("scan.txt")
   if err != nil {
      fmt.Println(err)
   }
   for {
      var i int
      var flt float64
      var str string
      var n int
      n, err = fmt.Fscanln(f, &str, &flt, &i)
      if n == 0 || err != nil {
        break
      }
      fmt.Println("string:", str, "; float:", flt, "; int:", i)
   }
}

输出结果:

string: SomeString ; float: 200 ; int: 2
string: OtherString ; float: 100.6 ; int: 9
string: OneMoreString ; float: 550.8 ; int: 1


<details>
<summary>英文:</summary>

Something like this might work--if you&#39;ve got spaces in your string, you might need to handle that differently:

    package main

    import (
      &quot;fmt&quot;
      &quot;os&quot;
    )

    func main() {
       f, err := os.Open(&quot;scan.txt&quot;)
       if err != nil {
          fmt.Println(err)
       }
       for {
          var i int
          var flt float64
          var str string
          var n int
          n, err = fmt.Fscanln(f, &amp;str, &amp;flt, &amp;i)
          if n == 0 || err != nil {
            break
          }
          fmt.Println(&quot;string:&quot;, str, &quot;; float:&quot;, flt, &quot;; int:&quot;, i)
       }
    }

outputs:

    string: SomeString ; float: 200 ; int: 2
    string: OtherString ; float: 100.6 ; int: 9
    string: OneMoreString ; float: 550.8 ; int: 1

</details>



# 答案2
**得分**: 0

例如,

    package main
    
    import (
    	"bufio"
    	"fmt"
    	"os"
    	"strconv"
    	"strings"
    )
    
    type Data struct {
    	AString string
    	AFloat  float64
    	AnInt   int64
    }
    
    func ParseLine(line string) (*Data, error) {
    	data := new(Data)
    	var err error
    	text := strings.TrimRight(line, " ")
    	i := strings.LastIndex(text, " ")
    	i++
    	text = text[i:]
    	data.AnInt, err = strconv.ParseInt(text, 10, 64)
    	if err != nil {
    		return nil, err
    	}
    	line = line[:i]
    	text = strings.TrimRight(line, " ")
    	i = strings.LastIndex(text, " ")
    	i++
    	text = text[i:]
    	data.AFloat, err = strconv.ParseFloat(text, 64)
    	if err != nil {
    		return nil, err
    	}
    	line = line[:i]
    	data.AString = line
    	return data, nil
    }
    
    func main() {
    	f, err := os.Open("data.txt")
    	if err != nil {
    		fmt.Fprintln(os.Stderr, "opening input:", err)
    		return
    	}
    	scanner := bufio.NewScanner(f)
    	for scanner.Scan() {
    		line := scanner.Text()
    		data, err := ParseLine(line)
    		if err != nil {
    			fmt.Fprintln(os.Stderr, "reading input:", err, ":", line)
    			continue
    		}
    		fmt.Println(*data)
    	}
    	if err := scanner.Err(); err != nil {
    		fmt.Fprintln(os.Stderr, "reading input:", err)
    	}
    }

输入(data.txt):

    Some String       200.0   2
    Other String      100.6   9
    One More String   550.8   1

输出:

    {Some String        200 2}
    {Other String       100.6 9}
    {One More String    550.8 1}

<details>
<summary>英文:</summary>

For example,

    package main
    
    import (
    	&quot;bufio&quot;
    	&quot;fmt&quot;
    	&quot;os&quot;
    	&quot;strconv&quot;
    	&quot;strings&quot;
    )
    
    type Data struct {
    	AString string
    	AFloat  float64
    	AnInt   int64
    }
    
    func ParseLine(line string) (*Data, error) {
    	data := new(Data)
    	var err error
    	text := strings.TrimRight(line, &quot; &quot;)
    	i := strings.LastIndex(text, &quot; &quot;)
    	i++
    	text = text[i:]
    	data.AnInt, err = strconv.ParseInt(text, 10, 64)
    	if err != nil {
    		return nil, err
    	}
    	line = line[:i]
    	text = strings.TrimRight(line, &quot; &quot;)
    	i = strings.LastIndex(text, &quot; &quot;)
    	i++
    	text = text[i:]
    	data.AFloat, err = strconv.ParseFloat(text, 64)
    	if err != nil {
    		return nil, err
    	}
    	line = line[:i]
    	data.AString = line
    	return data, nil
    }
    
    func main() {
    	f, err := os.Open(&quot;data.txt&quot;)
    	if err != nil {
    		fmt.Fprintln(os.Stderr, &quot;opening input:&quot;, err)
    		return
    	}
    	scanner := bufio.NewScanner(f)
    	for scanner.Scan() {
    		line := scanner.Text()
    		data, err := ParseLine(line)
    		if err != nil {
    			fmt.Fprintln(os.Stderr, &quot;reading input:&quot;, err, &quot;:&quot;, line)
    			continue
    		}
    		fmt.Println(*data)
    	}
    	if err := scanner.Err(); err != nil {
    		fmt.Fprintln(os.Stderr, &quot;reading input:&quot;, err)
    	}
    }

Input (data.txt):

    Some String       200.0   2
    Other String      100.6   9
    One More String   550.8   1

Output:

    {Some String        200 2}
    {Other String       100.6 9}
    {One More String    550.8 1}

</details>



huangapple
  • 本文由 发表于 2013年12月27日 21:45:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/20801820.html
匿名

发表评论

匿名网友

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

确定