python - 从未托管在谷歌云平台上的本地项目访问谷歌云 API
问题描述
我想从本地 python 代码中使用谷歌云自然语言 API。由于项目限制,我无法在 GCP 平台上运行我的代码。我有谷歌云帐户和积分来启用和使用 API。google 是否允许使用 API 在本地平台上运行。任何示例代码都会有所帮助。
解决方案
1.创建或选择一个项目。
gcloud projects create nat-lan-api
gcloud config set project nat-lan-api
2.启用计费。
gcloud alpha billing projects link nat-lan-api --billing-account XXXXXX-XXXXXX-XXXXXX
3.为该项目启用 Google Natural Language API。
gcloud services enable language.googleapis.com
3.创建一个服务帐户。
gcloud iam service-accounts create natural-language-api --description "natural-language-api" --display-name "natural-language-api"
gcloud iam service-accounts list
4.以 JSON 格式下载私钥。
gcloud iam service-accounts keys create key.json --iam-account natural-language-api@nat-lan-api.iam.gserviceaccount.com
5. 将环境变量 GOOGLE_APPLICATION_CREDENTIALS 设置为包含您的服务帐户密钥的 JSON 文件的路径。此变量仅适用于您当前的 shell 会话,因此如果您打开一个新会话,请再次设置该变量。
export GOOGLE_APPLICATION_CREDENTIALS="/Users/user/folder/key.json"
6.安装客户端库。
pip install --upgrade google-cloud-language
7.分析一些文本。
cat natural.py
# Imports the Google Cloud client library
from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types
# Instantiates a client
client = language.LanguageServiceClient()
# The text to analyze
text = u'Hello, world!'
document = types.Document(
content=text,
type=enums.Document.Type.PLAIN_TEXT)
# Detects the sentiment of the text
sentiment = client.analyze_sentiment(document=document).document_sentiment
print('Text: {}'.format(text))
print('Sentiment: {}, {}'.format(sentiment.score, sentiment.magnitude))
8.测试。
python natural.py
#Text: Hello, world!
#Sentiment: 0.30000001192092896, 0.30000001192092896
推荐阅读
- yocto - 如何修复此错误“sources/meta-qt5/recipes-qt/qt5/qtwayland_git.bb:do_configure) failed with exit code '1'”
- angular - 如何只下载一个 Angular Material 组件而不是整个库?
- flutter - Container inside Row 和 Row inside Container
- c++ - 如何为矩阵(2DArray)动态分配内存,其中行和列也是动态分配的?
- django - 我应该在请求另一个链接的 Heroku 上部署的我的 Django 应用程序中使用哪个用户代理
- linux - 扫雪机收集器不使用 https 协议(端口 443)
- javascript - 处理印刷机时正确附加到数组
- openwrt - 创建 procd 初始化脚本
- angular - Angular - 为什么将 Getter 用于非私有字段?
- react-native - React Native 如何获取设备的本地时间格式?