12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- package services
- import "fmt"
- func BatchTranslateHandlerByGoogle(contentMap map[string]string) (contentEnMap map[string]string, err error) {
- contentEnMap = make(map[string]string, 0)
- text := make([]string, 0)
- indexMap := make(map[int]string, 0)
- i := 0
- for k, v := range contentMap {
- indexMap[i] = k
- text = append(text, v)
- i++
- }
- contentEnList, err := GoogleCouldTranslateText("en", text)
- if err != nil {
- return
- }
- for k, v := range contentEnList {
- if in, ok := indexMap[k]; ok {
- contentEnMap[in] = v
- }
- }
- return
- }
- func SingleTranslateHandlerByGoogle(content string) (contentEn string, err error) {
- // 将内容切割成多段,进行翻译
- nameRune := []rune(content)
- num := len(nameRune)
- // Cloud Translation 基本版的请求大小上限为 100K 字节。Cloud Translation - Basic has a maximum request size of 100K bytes
- if len(content) >= 1200 {
- for i := 0; i < num; {
- text := make([]string, 0)
- last := i + 400
- if last >= num {
- last = num
- }
- tmp := string(nameRune[i:last])
- fmt.Printf("string(nameRune[%d:%d]) = %s", i, last, tmp)
- fmt.Println(" ")
- text = append(text, tmp)
- contentEnListTmp, e := GoogleCouldTranslateText("en", text)
- if e != nil {
- err = fmt.Errorf("翻译失败,Err:%s", e)
- return
- }
- if len(contentEnListTmp) > 0 {
- contentEn += contentEnListTmp[0]
- }
- i = last
- }
- fmt.Println(contentEn)
- } else {
- text := make([]string, 0)
- text = append(text, content)
- contentEnList, e := GoogleCouldTranslateText("en", text)
- if e != nil {
- err = fmt.Errorf("翻译失败,Err:%s", e)
- return
- }
- if len(contentEnList) > 0 {
- contentEn = contentEnList[0]
- }
- }
- return
- }
|