3 回答

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
解決方案:
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貢獻(xiàn)1817條經(jīng)驗(yàn) 獲得超14個(gè)贊
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貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
如果您想將文件切成兩半,那么您已經(jīng)完成了一半。數(shù)完單詞后,只需返回并再次讀取文件,將一半寫入一個(gè)文件,一半寫入另一個(gè)文件:
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是兩個(gè)輸出文件。
如果您不需要將文件切成兩半而只需將一半的單詞放在一個(gè)文件中,另一半放在另一個(gè)文件中,您可以一次完成,無需計(jì)數(shù)。當(dāng)您從第一個(gè)讀取時(shí),只需切換要寫入的文件:
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 關(guān)注
- 224 瀏覽
添加回答
舉報(bào)