📜  使用 Google Cloud 进行翻译和自然语言处理

📅  最后修改于: 2022-05-13 01:58:07.774000             🧑  作者: Mango

使用 Google Cloud 进行翻译和自然语言处理

先决条件:在 Google Cloud 上创建虚拟机并设置 API

在本文中,我们将讨论如何使用 Google Cloud 使用 Google 的翻译和自然语言处理功能。在阅读本文之前,您应该了解如何在虚拟机中创建实例以及如何设置 API(请参阅)。

翻译 API –

  • Google Translator API 的工作方式与此处相同。
  • 首先启用 Cloud Translation API 并按照此处的说明下载包含凭据信息的 .json 文件。

您需要下载以下软件包 –

pip install google.cloud
pip install google.cloud.translate

credetials.json文件与包含Python代码的.py文件保存在同一文件夹中。我们需要将credentials.json'(C:\Users\...)的路径保存为'GOOGLE_APPLICATION_CREDENTIALS',这已在以下代码的第5行中完成。



import os
import io
from google.cloud import translate
  
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] =
     os.path.join(os.curdir, 'credentials.json')
  
input_file = "filename_input.txt"
output_file = "filename_output.txt"
  
with io.open(input_file, "r", encoding ="utf-8") as inp:
     data = inp.read()
  
# The encoding needs to be utf-8 (Unicode) 
# because all languages are supported by
# Google Cloud and ASCII supports only English.
translate_client = translate.Client()
translated = list()
translated.append(translate_client.translate(
 data, target_language ='en')['translatedText'])
  
open(file = output_file, mode ='w', encoding ='utf-8',
        errors ='ignore').write('\n'.join(translated))

输入输出 .txt 文件应该与Python文件在同一个文件夹中,否则需要提供整个路径地址。输入文件应包含任何语言的源文本。用户无需指定语言,因为 Google 会自动检测。但是,目标语言需要以 ISO 639-1 代码的形式提供(例如,上面的代码将文本翻译成英文(由 'en' 编码))。

自然语言处理——

启用 Cloud Natural Language API 并下载“credentials.json”文件,如此处所述。您需要下载以下软件包 –

pip install google.cloud.language

Google 的自然语言处理 API 提供了多种分析文本的方法。所有这些都是语言分析的宝贵方面。

情绪分析:
它分析文本并理解文本的情感观点。 Sentiment Analysis 的输出是-1 到1 范围内的分数,其中-1 表示100% 的负面情绪,1 表示100% 的正面情绪,0 表示中性。它还输出一个范围从 0 到无穷大的幅度,表示情绪的整体强度。

import os
import io
from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types
  
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 
    os.path.join(os.curdir, 'credentials.json')
  
client = language.LanguageServiceClient()
input_file = "filename_input.txt"
with io.open(input_file, "r") as inp:
    docu = inp.read()
      
text = types.Document(content = docu, 
   type = enums.Document.Type.PLAIN_TEXT)
  
annotation = client.analyze_sentiment(document = text)
  
score = annotation.document_sentiment.score
magnitude = annotation.document_sentiment.magnitude
  
for index, sentence in enumerate(annotation.sentences):
    sentence_sentiment = sentence.sentiment.score
    print('Sentence #{} Sentiment score: {}'.format(
                     index + 1, sentence_sentiment))
  
print('Score: {}, Magnitude: {}'.format(score, magnitude))

文本应该出现在标题为filename_input.txt 。上面的代码会逐行分析并发布文本的情绪,也会提供整体的情绪。

Clearly Positive -> Score: 0.8, Magnitude: 3.0
Clearly Negative -> Score: -0.6, Magnitude: 4.0
Neutral -> Score: 0.1, Magnitude: 0.0
Mixed -> Score: 0.0, Magnitude: 4.0

这是通过情感分析附加到文本的情感的大致性质。

实体分析:
实体分析提供有关文本中实体的信息,这些实体一般指命名的“事物”,例如名人、地标、常见物体等。

import os
import io
from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types
  
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 
    os.path.join(os.curdir, 'credentials.json')
  
client = language.LanguageServiceClient()
input_file = "filename_input.txt"
with io.open(input_file, "r") as inp:
    docu = inp.read()
      
text = types.Document(content = docu, 
    type = enums.Document.Type.PLAIN_TEXT)
  
ent = client.analyze_entities(document = text)
  
entity = ent.entities
  
for e in entity:
    print(e.name, e.metadata, e, type, e.salience)

上面的代码将从上述文本中提取所有实体,命名其类型、显着性(即实体的显着性)及其元数据(主要用于专有名词,以及该实体的维基百科链接)语法分析:
语法分析将给定文本分解为标记(默认为一系列单词)并提供有关这些标记的语言信息。

import os
import io
from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types
  
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 
     os.path.join(os.curdir, 'credentials.json')
  
client = language.LanguageServiceClient()
input_file = "filename_input.txt"
with io.open(input_file, "r") as inp:
    docu = inp.read()
      
text = types.Document(content = docu,
    type = enums.Document.Type.PLAIN_TEXT)
  
tokens = client.analyze_syntax(text).tokens
  
for token in tokens:
    speech_tag = enums.PartOfSpeech.Tag(token.part_of_speech.tag)
    print(u'{}: {}'.format(speech_tag.name, token.text.content))

上面的代码提供了所有单词及其语法的列表,无论是名词、动词、代词、标点符号等。有关更多信息,请在此处访问 Google Natural Language API 文档。

因此,Google Cloud API 提供了易于使用、可移植、简短且清晰的高功能服务。

笔记:
有时,上述程序会导致错误“ImportError: Cannot import name 'cygrpc'”,当我们尝试使用安装它时出现问题

pip install cygrpc
or
sudo apt-get install cygrpc

而是使用以下命令:

python -m pip install grpcio --ignore-installed