61 lines
1.4 KiB
Go
61 lines
1.4 KiB
Go
package main
|
|
|
|
import (
|
|
"math/rand"
|
|
"os"
|
|
)
|
|
|
|
// ChineseDict represents a dictionary containing Chinese characters
|
|
type ChineseDict struct {
|
|
characters []rune
|
|
}
|
|
|
|
// NewChineseDict creates a new ChineseDict instance and loads content from dict.txt
|
|
func NewChineseDict(filePath string) (*ChineseDict, error) {
|
|
// Read the file content
|
|
content, err := os.ReadFile(filePath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Convert bytes to string and then to runes to properly handle Chinese characters
|
|
text := string(content)
|
|
runes := []rune(text)
|
|
|
|
return &ChineseDict{
|
|
characters: runes,
|
|
}, nil
|
|
}
|
|
|
|
// GetRandomCharacter returns a random Chinese character from the dictionary
|
|
func (cd *ChineseDict) GetRandomCharacter() rune {
|
|
if len(cd.characters) == 0 {
|
|
return 0 // Return null rune if no characters available
|
|
}
|
|
|
|
// Get random index
|
|
randomIndex := rand.Intn(len(cd.characters))
|
|
|
|
return cd.characters[randomIndex]
|
|
}
|
|
|
|
// GetRandomString returns a string of random Chinese characters with specified length
|
|
func (cd *ChineseDict) GetRandomString(length int) string {
|
|
if len(cd.characters) == 0 || length <= 0 {
|
|
return ""
|
|
}
|
|
|
|
result := make([]rune, length)
|
|
for i := 0; i < length; i++ {
|
|
randomIndex := rand.Intn(len(cd.characters))
|
|
result[i] = cd.characters[randomIndex]
|
|
}
|
|
|
|
return string(result)
|
|
}
|
|
|
|
// GetCharacterCount returns the total number of Chinese characters in the dictionary
|
|
func (cd *ChineseDict) GetCharacterCount() int {
|
|
return len(cd.characters)
|
|
}
|