Ani*_*mar 5 python nlp google-cloud-platform
我想从本地 python 代码使用谷歌云自然语言 API。由于项目限制,我无法在 GCP 平台上运行我的代码。我有谷歌云帐户和积分来启用和使用 API。谷歌是否允许使用 API 在本地平台上运行。任何示例代码都会有所帮助。
1.创建或选择一个项目。
gcloud projects create nat-lan-api
gcloud config set project nat-lan-api
Run Code Online (Sandbox Code Playgroud)
2.启用计费。
gcloud alpha billing projects link nat-lan-api --billing-account XXXXXX-XXXXXX-XXXXXX
Run Code Online (Sandbox Code Playgroud)
3. 为该项目启用 Google Natural Language API。
gcloud services enable language.googleapis.com
Run Code Online (Sandbox Code Playgroud)
3.创建服务帐户。
gcloud iam service-accounts create natural-language-api --description "natural-language-api" --display-name "natural-language-api"
gcloud iam service-accounts list
Run Code Online (Sandbox Code Playgroud)
4.下载 JSON 格式的私钥。
gcloud iam service-accounts keys create key.json --iam-account natural-language-api@nat-lan-api.iam.gserviceaccount.com
Run Code Online (Sandbox Code Playgroud)
5.将环境变量 GOOGLE_APPLICATION_CREDENTIALS 设置为包含服务帐户密钥的 JSON 文件的路径。该变量仅适用于当前的 shell 会话,因此如果您打开新会话,请再次设置该变量。
export GOOGLE_APPLICATION_CREDENTIALS="/Users/user/folder/key.json"
Run Code Online (Sandbox Code Playgroud)
6.安装客户端库。
pip install --upgrade google-cloud-language
Run Code Online (Sandbox Code Playgroud)
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))
Run Code Online (Sandbox Code Playgroud)
8.测试。
python natural.py
#Text: Hello, world!
#Sentiment: 0.30000001192092896, 0.30000001192092896
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
217 次 |
| 最近记录: |