检测文本语言 返回语言代码:en(英文), zh(中文), ja(日文) 等
(self, text)
| 39 | OUTPUT_IS_LIST = (True,) |
| 40 | |
| 41 | def detect_language(self, text): |
| 42 | """ |
| 43 | 检测文本语言 |
| 44 | 返回语言代码:en(英文), zh(中文), ja(日文) 等 |
| 45 | """ |
| 46 | if not text or not text.strip(): |
| 47 | return "en" |
| 48 | |
| 49 | # 检测中文字符 |
| 50 | chinese_pattern = re.compile(r'[\u4e00-\u9fff]') |
| 51 | chinese_count = len(chinese_pattern.findall(text)) |
| 52 | |
| 53 | # 检测日文字符(平假名、片假名) |
| 54 | japanese_pattern = re.compile(r'[\u3040-\u309f\u30a0-\u30ff]') |
| 55 | japanese_count = len(japanese_pattern.findall(text)) |
| 56 | |
| 57 | # 检测韩文字符 |
| 58 | korean_pattern = re.compile(r'[\uac00-\ud7a3]') |
| 59 | korean_count = len(korean_pattern.findall(text)) |
| 60 | |
| 61 | # 检测英文字符 |
| 62 | english_pattern = re.compile(r'[a-zA-Z]') |
| 63 | english_count = len(english_pattern.findall(text)) |
| 64 | |
| 65 | # 根据字符数量判断语言 |
| 66 | total_chars = len(text) |
| 67 | |
| 68 | if chinese_count > total_chars * 0.3: |
| 69 | return "zh" |
| 70 | elif japanese_count > total_chars * 0.2: |
| 71 | return "ja" |
| 72 | elif korean_count > total_chars * 0.2: |
| 73 | return "ko" |
| 74 | else: |
| 75 | return "en" |
| 76 | |
| 77 | def convert_to_json(self, text, lang="en"): |
| 78 | """ |