import ddddocr
def recognize_captcha(image_path='1.png'):
"""识别图片验证码"""
ocr = ddddocr.DdddOcr(show_ad=False)
try:
with open(image_path, 'rb') as f:
code = f.read()
res = ocr.classification(code)
print(f"图片验证码为:{res}")
return res
except Exception as e:
print(f"验证码识别出错: {e}")
return None
def calculate_result(expression):
"""计算验证码中的数学表达式"""
try:
# 处理带等号的表达式
if '=' in expression:
expression = expression.split('=')[0]
# 识别运算符并计算
if 'x' in expression or '*' in expression:
# 处理乘法
operator = 'x' if 'x' in expression else '*'
a, b = expression.split(operator)
result = int(a) * int(b)
elif '+' in expression:
# 处理加法
a, b = expression.split('+')
result = int(a) + int(b)
elif '-' in expression:
# 处理减法
a, b = expression.split('-')
result = int(a) - int(b)
else:
# 无法识别的表达式
return None
print(f'计算结果:{result}')
return result
except Exception as e:
print(f"计算出错: {e}")
return None
def main():
"""主函数"""
while True:
# 识别验证码
captcha_text = recognize_captcha()
# 验证码格式检查
if not captcha_text or len(captcha_text) < 3 or not captcha_text[0].isdigit() or captcha_text == '=':
print("验证码格式不正确,重新获取...")
continue
# 计算结果
result = calculate_result(captcha_text)
if result is not None:
# 这里可以添加使用计算结果的代码
print(f"最终结果: {result}")
break
else:
print("无法计算结果,重新获取验证码...")
if __name__ == "__main__":
main()