📅  最后修改于: 2023-12-03 15:15:24.541000             🧑  作者: Mango
Google Translate 是由 Google 公司开发的一款翻译工具。它支持超过 100 种语言之间的翻译,包括文字、语音和图像翻译。
Google Translate 的主要功能之一是文字翻译。用户可以输入待翻译的文本,选择语言,Google Translate 就可以快速翻译成目标语言。
import urllib.parse
import urllib.request
text = 'Hello, world!'
target_language = 'zh-CN'
url = 'https://translate.google.com/translate_a/single?' + \
'client=at&dt=t&dt=ld&dt=qca&dt=rm&dt=bd&' + \
'dj=1&ie=UTF-8&sl=auto&tl=' + target_language + \
'&q=' + urllib.parse.quote(text)
response = urllib.request.urlopen(url).read().decode('utf-8')
print(response)
Google Translate 还支持语音翻译。用户可以录制待翻译的语音,Google Translate 会自动识别语言并翻译成目标语言。
import io
import os
from google.cloud import speech
from google.cloud.speech import enums
from google.cloud.speech import types
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'path/to/credentials.json'
client = speech.SpeechClient()
language_code = 'en-US'
config = types.RecognitionConfig(
encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=16000,
language_code=language_code)
streaming_config = types.StreamingRecognitionConfig(
config=config,
interim_results=True)
def process_audio(streaming_config, audio_data):
recognize_stream = client.streaming_recognize(streaming_config)
with io.BytesIO(audio_data) as audio_stream:
requests = (
types.StreamingRecognizeRequest(audio_content=content)
for content in generate_chunks(audio_stream)
)
responses = recognize_stream.iter_requests(requests)
for response in responses:
print(response)
process_audio(streaming_config, audio_data)
Google Translate 还支持图像翻译。用户可以拍照或上传图片,Google Translate 会自动识别语言并翻译成目标语言。
import io
from google.cloud import vision
from google.cloud.vision import types
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'path/to/credentials.json'
client = vision.ImageAnnotatorClient()
def process_image(image_path, target_language):
with io.open(image_path, 'rb') as image_file:
content = image_file.read()
image = types.Image(content=content)
response = client.text_detection(image=image)
text = response.full_text_annotation.text
print(text)
url = 'https://translate.google.com/translate?' + \
'hl=en&sl=auto&tl=' + target_language + \
'&text=' + urllib.parse.quote(text)
response = urllib.request.urlopen(url).read().decode('utf-8')
print(response)
Google Translate 可以通过网页、浏览器扩展、移动应用程序和 API 进行使用。
无论是在日常生活中还是在开发过程中,翻译都是一个必不可少的工具。Google Translate 通过其强大的文字翻译、语音翻译和图像翻译功能,帮助用户更轻松地进行语言沟通,并为程序员提供了更便利的开发工具。