3 回答

TA贡献1810条经验 获得超4个赞
解决方案:
var s []string
.
.
.
for scanner.Scan() {// storing or appending file.txt string values to array s.
s = append(s, scanner.Text())
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
//writing to file1 and file2
if len(s)%2 == 0 { // if the occurences of words is an even number.
for i := 0; i <= len(s)/2-1; i++ { // Writing first half of words to file1
fmt.Fprintln(file1, s[i])
}
for j := len(s) / 2; j < len(s); j++ { // Writing second half of words to file2
fmt.Fprintln(file2, s[j])
}
} else { // if the occurences of words is an odd number.
for i := 0; i <= len(s)/2; i++ { // Writing first part of words to file1
fmt.Fprintln(file1, s[i])
}
for j := len(s)/2 + 1; j < len(s); j++ { // Writing second part of words to file2
fmt.Fprintln(file2, s[j])
}
}
.
.
.

TA贡献1817条经验 获得超14个赞
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
WordbyWordScan()
}
func WordbyWordScan() {
file, err := os.Open("file.txt.txt")
if err != nil {
log.Fatal(err)
}
file1, err := os.Create("file1.txt.txt")
if err != nil {
panic(err)
}
file2, err := os.Create("file2.txt.txt")
if err != nil {
panic(err)
}
defer file.Close()
defer file1.Close()
defer file2.Close()
file.Seek(0, 0)
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanWords)
w := 0
for scanner.Scan() {
var outfile *os.File
if w%2 == 0 {
outfile = file1
} else {
outfile = file2
}
fmt.Fprintln(outfile, scanner.Text())
w++
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}

TA贡献1802条经验 获得超5个赞
如果您想将文件切成两半,那么您已经完成了一半。数完单词后,只需返回并再次读取文件,将一半写入一个文件,一半写入另一个文件:
file.Seek(0,0)
scanner = bufio.NewScanner(file)
scanner.Split(bufio.ScanWords)
w:=0
for scanner.Scan() {
var outfile *os.File
if w<count/2 {
outfile=file1
} else {
outfile=file2
}
fmt.Fprintln(outfile,scanner.Text())
w++
}
上面,file1和file2是两个输出文件。
如果您不需要将文件切成两半而只需将一半的单词放在一个文件中,另一半放在另一个文件中,您可以一次完成,无需计数。当您从第一个读取时,只需切换要写入的文件:
w:=0
for scanner.Scan() {
var outfile *os.File
if w%2==0 {
outfile=file1
} else {
outfile=file2
}
fmt.Fprintln(outfile,scanner.Text())
w++
}
- 3 回答
- 0 关注
- 227 浏览
添加回答
举报