Python调用百度智能云:文字识别(每天一个python小项目)

from aip import AipOcr
import requests
from requests.exceptions import RequestException
import tkinter as tk
from PIL import Image, ImageTk
import tkinter.filedialog

def wenzi():
    APP_ID = 'XXX'
    API_KEY = 'XXX'
    SECRET_KEY = 'XXX'

    aip_orc = AipOcr(APP_ID, API_KEY, SECRET_KEY)
    file_path = tk.filedialog.askopenfilename()

    def get_file_content(file_path):
        with open(file_path, 'rb') as f:
            return f.read()

    options = {}
    options['language_type'] = 'true'
    options['detect_direction'] = 'true'
    options['detect_language'] = 'true'
    result = aip_orc.basicAccurate(get_file_content(file_path), options)
    a = ''
    for i in range(len(result['words_result'])):
        a = a + ' ' + result['words_result'][i]['words']
    text.delete(1.0, "end")  # 清空输出文本框
    text.insert('end', a)  # 将翻译结果添加到输出文本框中

#定义清空文本框的函数
def delete():
  text.delete(1.0,"end")  

window = tk.Tk()  #创建window窗口
window.title("文字识别器")  # 定义窗口名称
text = tk.Text(window, height=18) 
text.grid(row=0)

# 添加一个按钮,用于触发识别功能
t_button = tk.Button(window, text='识别', relief=tk.RAISED, width=8, height=1,font='宋体',bg='red',fg='white',command=wenzi)
# 添加一个按钮,用于触发清空输出文本框
button2 = tk.Button(window, text='清空',font='宋体', relief=tk.RAISED,width=8, height=1, command=delete)
#完成界面布局,设置各个控件的位置
t_button.grid(row=0,column=1,padx=2)
button2.grid(row=0,column=3,padx=2)
tk.mainloop()

运行结果:
Python调用百度智能云:文字识别(每天一个python小项目)_第1张图片

你可能感兴趣的:(每天一个python小项目,python,开发语言)