translate.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package services
  2. import "fmt"
  3. func BatchTranslateHandlerByGoogle(contentMap map[string]string) (contentEnMap map[string]string, err error) {
  4. contentEnMap = make(map[string]string, 0)
  5. text := make([]string, 0)
  6. indexMap := make(map[int]string, 0)
  7. i := 0
  8. for k, v := range contentMap {
  9. indexMap[i] = k
  10. text = append(text, v)
  11. i++
  12. }
  13. contentEnList, err := GoogleCouldTranslateText("en", text)
  14. if err != nil {
  15. return
  16. }
  17. for k, v := range contentEnList {
  18. if in, ok := indexMap[k]; ok {
  19. contentEnMap[in] = v
  20. }
  21. }
  22. return
  23. }
  24. func SingleTranslateHandlerByGoogle(content string) (contentEn string, err error) {
  25. // 将内容切割成多段,进行翻译
  26. nameRune := []rune(content)
  27. num := len(nameRune)
  28. // Cloud Translation 基本版的请求大小上限为 100K 字节。Cloud Translation - Basic has a maximum request size of 100K bytes
  29. if len(content) >= 1200 {
  30. for i := 0; i < num; {
  31. text := make([]string, 0)
  32. last := i + 400
  33. if last >= num {
  34. last = num
  35. }
  36. tmp := string(nameRune[i:last])
  37. fmt.Printf("string(nameRune[%d:%d]) = %s", i, last, tmp)
  38. fmt.Println(" ")
  39. text = append(text, tmp)
  40. contentEnListTmp, e := GoogleCouldTranslateText("en", text)
  41. if e != nil {
  42. err = fmt.Errorf("翻译失败,Err:%s", e)
  43. return
  44. }
  45. if len(contentEnListTmp) > 0 {
  46. contentEn += contentEnListTmp[0]
  47. }
  48. i = last
  49. }
  50. fmt.Println(contentEn)
  51. } else {
  52. text := make([]string, 0)
  53. text = append(text, content)
  54. contentEnList, e := GoogleCouldTranslateText("en", text)
  55. if e != nil {
  56. err = fmt.Errorf("翻译失败,Err:%s", e)
  57. return
  58. }
  59. if len(contentEnList) > 0 {
  60. contentEn = contentEnList[0]
  61. }
  62. }
  63. return
  64. }