Представьте себе, что у вас есть testfile.txt
:
this is fine
Вы можете использовать этот go-скрипт для циклического перебора каждого слова и печати слова с его текущей позицией:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
// initiate file-handle to read from
fileHandle, err := os.Open("testfile.txt")
// check if file-handle was initiated correctly
if err != nil {
panic(err)
}
// make sure to close file-handle upon return
defer fileHandle.Close()
// initiate scanner from file handle
fileScanner := bufio.NewScanner(fileHandle)
// tell the scanner to split by words
fileScanner.Split(bufio.ScanWords)
// initiate counter
count := 0
// for looping through results
for fileScanner.Scan() {
fmt.Printf("word: '%s' - position: '%d'\n", fileScanner.Text(), count)
count++
}
// check if there was an error while reading words from file
if err := fileScanner.Err(); err != nil {
panic(err)
}
// print total word count
fmt.Printf("total word count: '%d'", count)
}
Вывод:
$ go run main.go
word: 'this' - position: '0'
word: 'is' - position: '1'
word: 'fine' - position: '2'
total word count: '3'
Если вы хотите сравнить слова по индексу, вы можете сначала загрузить их в фрагмент.
Представьте, что у вас есть текстовый файл:
fine this is fine
Используйте этокод:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
// initiate file-handle to read from
fileHandle, err := os.Open("testfile.txt")
// check if file-handle was initiated correctly
if err != nil {
panic(err)
}
// make sure to close file-handle upon return
defer fileHandle.Close()
// initiate scanner from file handle
fileScanner := bufio.NewScanner(fileHandle)
// tell the scanner to split by words
fileScanner.Split(bufio.ScanWords)
// initiate wordsSlice
var wordSlice []string
// for looping through results
for fileScanner.Scan() {
wordSlice = append(wordSlice, fileScanner.Text())
}
// check if there was an error while reading words from file
if err := fileScanner.Err(); err != nil {
panic(err)
}
// loop through word slice and print word with index
for i, w := range wordSlice {
fmt.Printf("word: '%s' - position: '%d'\n", w, i)
}
// compare words by index
firstWordPos := 0
equalsWordPos := 3
if wordSlice[firstWordPos] == wordSlice[equalsWordPos] {
fmt.Printf("word at position '%d' and '%d' is equal: '%s'\n", firstWordPos, equalsWordPos, wordSlice[firstWordPos])
}
// print total word count
fmt.Printf("total word count: '%d'", len(wordSlice))
}
Выход:
$ go run main.go
word: 'fine' - position: '0'
word: 'this' - position: '1'
word: 'is' - position: '2'
word: 'fine' - position: '3'
word at position '0' and '3' is equal: 'fine'
total word count: '4'