通过Python实现图像识别+翻译功能

该程序使用pytesseract进行图像文字识别,将识别结果保存至read.txt。用户可以选择对识别内容或输入文档进行英译中翻译。若文本过长,会提示使用文档识别功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用到的库文件

pytesseract

PIL

translate

代码

import pytesseract
from PIL import Image
from translate import Translator


def countword(s):
    return s.split(" ")

# 将长段落分句
def longarticle_divide(s):
    return s.split(".")


print("欢迎使用本程序")
print("本程序提供图文识别、英译中服务")
print("是否需要图文识别(Y/N)")
choice1 = input()

if choice1 == "Y":
    # 读取图片
    im = Image.open('1.png')

    # 识别文字
    string = pytesseract.image_to_string(im)

    # 写入文件
    file = open('read.txt', 'w')
    file.write(string)
    file.close()
    print("识别成功,已写入read.txt")
    # 翻译
    print("请选择是否需要翻译(Y/N)")
    choice = input()
    if choice == 'Y':
        print("请选择翻译内容")
        print("1.图文识别结果\n2.文档识别")
        choice2 = input()
        if choice2 == '1':
            num = countword(string)
            if len(num) < 500:
                translator = Translator(to_lang="zh")
                translation = translator.translate(string)
                print(translation)
                file = open('read.txt', 'w')
                file.writelines(translation)
                file.close()
            else:
                print("文章长度超过限制,请使用文档识别")
        else:
            print("请输入文档名称")
            filename = input()
            file = open(filename, 'r')
            word = file.read()
            s = longarticle_divide(word)
            for i in s:
                translator = Translator(to_lang="zh")
                translation = translator.translate(i)
                print(translation+'\n')
    else:
        print("感谢使用")
else:
    print("请选择是否需要翻译(Y/N)")
    choice3 = input()
    if choice3 == 'Y':
        print("请输入文档名称")
        filename = input()
        file = open(filename, 'r')
        word = file.read()
        s = longarticle_divide(word)
        for i in s:
            translator = Translator(to_lang="zh")
            translation = translator.translate(i)
            print(translation+'\n')
    else:
        print("感谢使用")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值