英文:
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 < 3 {
_, err := buf.WriteString("\n")
if err != nil {
exit("Couldn't replace line")
}
}
}
</details>
# 答案1
**得分**: 1
你的程序缺少两个部分,首先,你应该将行的内容写入`buf`,所以`_, err := buf.WriteString("\n")`可以改写为:
```go
_, err := buf.WriteString(text + "\n")
第二个部分是删除代码,最简单的方法是在将buf
的内容转储到文件处理程序之前使用Seek
和Truncate
两者:
// 重置文件大小
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("\n")
could be rewritten as:
_, err := buf.WriteString(text + "\n")
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 (
"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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论