func WordbyWordScan() { //A function for dividing a text file into two file texts.
file, err := os.Open("file.txt.txt") //Open a file for doing operation on it.
if err != nil {
log.Fatal(err)
}
file1, err := os.Create("file1.txt.txt") //Create a file
if err != nil {
panic(err)
}
file2, err := os.Create("file2.txt.txt") //Create a file
if err != nil {
panic(err)
}
defer file.Close() //close file at the end.
defer file1.Close() //close file at the end.
defer file2.Close() //close file at the end.
file.Seek(0, 0) // "Seek sets the offset for the next Read or Write on file to offset."
scanner := bufio.NewScanner(file) // "NewScanner returns a new Scanner to read from file"
scanner.Split(bufio.ScanWords) // "Set the split function for the scanning operation."
w := 0
for scanner.Scan() { //writing to file1 and file2
var outfile *os.File
if w%2 == 0 {
outfile = file1
} else {
outfile = file2
}
fmt.Fprintln(outfile, scanner.Text()) //"Fprintln formats using the default formats for its operands and writes to outfile."
w++
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}
This code above, split the file.txt word by word instead of splitting the first half of words and then the second half in order. For example, this sentence “Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer object, creating another object.” should be split like this:
First half: “Package bufio implements buffered I/O. It wraps an io”
Second half: “.Reader or io.Writer object, creating another object.”
If anyone has any idea to fix this, I look forward to hearing from you.