在Python脚本中使用API microsoft translator

2024-05-20 18:21:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python编写一个脚本,用于检测所提供文本的语言

我发现以下命令行可以在终端中工作,但我想在脚本中使用它

命令:

**curl -X POST "https://api.cognitive.microsofttranslator.com/detect?api-version=3.0" -H "Ocp-Apim-Subscription-Key: <client-secret>" -H "Content-Type: application/json" -d "[{'Text':'What language is this text written in?'}]"**.

在脚本中,诸如客户机机密、“text”等元素。。。应该在变量中。我希望在变量中捕获整个命令行的结果,然后将其打印给用户

我该怎么做

我找到了命令行here


Tags: text命令行https文本命令脚本comapi
1条回答
网友
1楼 · 发布于 2024-05-20 18:21:50

Command Line中的命令实际上是发送http request。因此,您只需要使用我在下面提供的python代码,仅供参考

import requests
import json

url = 'https://api.cognitive.microsofttranslator.com//Detect?api-version=3.0'
body =[{"text": "你好"}]
headers = {'Content-Type': 'application/json',"Ocp-apim-subscription-key": "b12776c*****14f5","Ocp-apim-subscription-region": "koreacentral"}
r = requests.post(url, data=json.dumps(body), headers=headers)
result=json.loads(r.text)
a=result[0]["language"]
print(r.text)
print("Language = " + a)

enter image description here

相关问题 更多 >