在 Python 脚本中使用 API microsoft 翻译器 [英] Using API microsoft translator in a Python script

查看:33
本文介绍了在 Python 脚本中使用 API microsoft 翻译器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 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':'这段文字是用什么语言写的?'}]"**.

在脚本中,像客户端机密、text"等元素应该在变量中.我想在一个变量中捕获整个命令行的结果,然后将其打印给用户.

我该怎么做?

我找到了命令行

I am writing a script in Python that detects the language of a provided text.

I found the following command line that works in a terminal, but I would like to use it in my script.

Command :

**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?'}]"**.

In the script, elements like the client-secret, the "text", and so on... should be in variables. And I would like to catch the result of the whole command line in a variable and then print it to the user.

How can I do this?

I found the command line here.

解决方案

The command in Command Line is essentially sending http request. So you just need to use the python code I provide below, just for reference.

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)

这篇关于在 Python 脚本中使用 API microsoft 翻译器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆