如何用DeepL Python库/原生API检测源语言(无需翻译)?
DeepL API/Python客户端实现无翻译的源语言检测
可以实现,DeepL的API确实支持单独的源语言检测功能,以下是具体实现路径:
Python客户端库实现
使用官方deepl Python库的detect_language方法,该方法仅执行语言检测,不会触发翻译操作。
- 先安装库:
pip install deepl
- 代码示例:
import deepl # 替换为你的DeepL API密钥 translator = deepl.Translator("YOUR_AUTH_KEY") # 检测单段文本 single_result = translator.detect_language("Hello, this is a test.") print(f"语言代码: {single_result.language}, 置信度: {single_result.confidence}") # 批量检测多段文本 multi_results = translator.detect_language(["Bonjour tout le monde", "こんにちは"]) for res in multi_results: print(f"文本: {res.text}, 语言: {res.language}, 置信度: {res.confidence}")
返回结果包含语言代码(如en、fr)和置信度(0-1之间的数值,代表检测结果的可靠程度)。
原生API实现
直接调用DeepL API的/v2/detect端点,发送POST请求即可,无需指定目标语言参数:
import requests auth_key = "YOUR_AUTH_KEY" api_url = "https://api.deepl.com/v2/detect" # 单文本检测 payload = { "auth_key": auth_key, "text": "Guten Tag, wie geht es dir?" } response = requests.post(api_url, data=payload) detect_result = response.json()[0] print(f"语言代码: {detect_result['language']}, 置信度: {detect_result['confidence']}")
如果是批量检测,只需将text参数设为包含多段文本的列表即可。
注意:确保使用的deepl Python库为v1.10及以上版本,旧版本可能未提供该方法;免费版API同样支持语言检测功能,无需升级付费套餐。
内容的提问来源于stack exchange,提问作者Bastian Venthur
相关产品推荐
相关产品推荐

