python诞生30周年
# encoding:utf-8
import requests
import base64
from PIL import Image
import pytesseract
# 这里需要安装一下 Tesseract-OCR
# 链接:https://pan.baidu.com/s/1D2eODet7x9xshBVi6ZUZ_Q
# 提取码:qfef
# 安装好之后别忘了把Tesseract-OCR路径添加到环境变量中
import json
import requests
import keyboard #监听按键库
from PIL import ImageGrab #图像处理库
import time
from aip import AipOcr #pip install baidu_aip
# print("开始截图")
# 1. 截取图片
keyboard.wait(hotkey='ctrl+alt+a')
# print("键盘按下了'ctrl+alt+a'")
keyboard.wait('enter')
# print("键盘按下了'enter'")
# 模拟延迟,来解决grabclipboard函数的缓存问题(grabclipboard函数操作太快,它就会读取上一次的内容)
time.sleep(0.1)
# 2. 保存图片到电脑上
image = ImageGrab.grabclipboard()
image.save('screen.png')
#*************************************************************************************
request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"
# 二进制方式打开图片文件
f = open('screen.png', 'rb')
img = base64.b64encode(f.read())
params = {"image":img}
access_token = "你自己的access_token,百度AI里面有教程,我把网址放下面了"
# https://ai.baidu.com/ai-doc/OCR/vk3h7y58v
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.post(request_url, data=params, headers=headers)
print("文字识别:")
if response:
locList = response.json()['words_result']
for i in locList:
print(i['words'])
print("\n翻译:")
if response:
locList = response.json()['words_result']
for i in locList:
text = i['words']
##================================================================================##
# 翻译函数,word 需要翻译的内容
def translate(word):
# 有道词典 api
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null'
# 传输的参数,其中 i 为需要翻译的内容
key = {
'type': "AUTO",
'i': word,
"doctype": "json",
"version": "2.1",
"keyfrom": "fanyi.web",
"ue": "UTF-8",
"action": "FY_BY_CLICKBUTTON",
"typoResult": "true"
}
# key 这个字典为发送给有道词典服务器的内容
response = requests.post(url, data=key)
# 判断服务器是否相应成功
if response.status_code == 200:
# 然后相应的结果
return response.text
else:
print("有道词典调用失败")
# 失败就返回空
return None
def get_reuslt(repsonse):
# 通过 json.loads 把返回的结果加载成 json 格式
result = json.loads(repsonse)
print("%s" % result['translateResult'][0][0]['tgt'])
def main():
list_trans = translate(text)
get_reuslt(list_trans)
if __name__ == '__main__':
main()
最后祝大家圣诞节快乐呦!