如何从文件中删除短文本行

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

How to remove short lines of text from a file

问题

我正在尝试编写一个Go程序,它将读取一个.txt文件,并删除所有长度小于指定长度的行。我试图在读取文件时进行操作,它确实找到了所有长度为2的行,但没有将它们删除。

scanner := bufio.NewScanner(file)
var bs []byte
buf := bytes.NewBuffer(bs)

var text string
for scanner.Scan() {
    text = scanner.Text()
    length := len(text)
    if length < 3 {
        _, err := buf.WriteString("\n")
        if err != nil {
            exit("无法替换行")
        }
    }
}
英文:

I am trying to write a Go program that will read a .txt file and will remove all lines that are shorter than the specified amount.
I am trying to do it as I am reading the file, it actually does find all the lines that are 2 symbols long, but doesn't remove them.

    scanner := bufio.NewScanner(file)
    var bs []byte
    buf := bytes.NewBuffer(bs)
    
    var text string
    for scanner.Scan() {
    	text = scanner.Text()
    	length := len(text)
    	if length &lt; 3 {
    		_, err := buf.WriteString(&quot;\n&quot;)
    		if err != nil {
    			exit(&quot;Couldn&#39;t replace line&quot;)
    		}
    	}
    }	

</details>


# 答案1
**得分**: 1

你的程序缺少两个部分,首先,你应该将行的内容写入`buf`,所以`_, err := buf.WriteString("\n")`可以改写为:

```go
_, err := buf.WriteString(text + "\n")

第二个部分是删除代码,最简单的方法是在将buf的内容转储到文件处理程序之前使用SeekTruncate两者:

// 重置文件大小
f.Truncate(0)
// 定位到文件的开头:
f.Seek(0, 0)
// 最后将buf的内容写入文件:
buf.WriteTo(f)

完整的程序如下:

package main

import (
	"bufio"
	"bytes"
	"os"
)

func main() {
	f, err := os.OpenFile("input.txt", os.O_RDWR, 0644)
	if err != nil {
		panic(err)
	}
	scanner := bufio.NewScanner(f)
	var bs []byte
	buf := bytes.NewBuffer(bs)

	var text string
	for scanner.Scan() {
		text = scanner.Text()
		length := len(text)
		if length < 3 {
			_, err := buf.WriteString(text + "\n")
			if err != nil {
				panic("Couldn't replace line")
			}
		}
	}
	f.Truncate(0)
	f.Seek(0, 0)
	buf.WriteTo(f)
}
英文:

Your program is missing two things, first you should write the contents of the line to buf, so _, err := buf.WriteString(&quot;\n&quot;) could be rewritten as:

_, err := buf.WriteString(text + &quot;\n&quot;)

The second thing is the removal code, the simplest approach could be to use both Seek and Truncate before dumping the contents of buf to the file handler:

// Reset the file size
f.Truncate(0)
// Position on the beginning of the file:
f.Seek(0, 0)
// Finally write the contents of buf into the file:
buf.WriteTo(f)

The full program would look like:

package main

import (
	&quot;bufio&quot;
	&quot;bytes&quot;
	&quot;os&quot;
)

func main() {
	f, err := os.OpenFile(&quot;input.txt&quot;, os.O_RDWR, 0644)
	if err != nil {
		panic(err)
	}
	scanner := bufio.NewScanner(f)
	var bs []byte
	buf := bytes.NewBuffer(bs)

	var text string
	for scanner.Scan() {
		text = scanner.Text()
		length := len(text)
		if length &lt; 3 {
			_, err := buf.WriteString(text + &quot;\n&quot;)
			if err != nil {
				panic(&quot;Couldn&#39;t replace line&quot;)
			}
		}
	}
	f.Truncate(0)
	f.Seek(0, 0)
	buf.WriteTo(f)
}

huangapple
  • 本文由 发表于 2021年10月29日 05:20:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/69761074.html
匿名

发表评论

匿名网友

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

确定