pip install ddddocr
import ddddocr
import requests
import re
class RegularCalculation:
__div = re.compile(r"(\d+\.?\d*/-\d+\.?\d*)|(\d+\.?\d*/\d+\.?\d*)")
__mul = re.compile(r"(\d+\.?\d*\*-\d+\.?\d*)|(\d+\.?\d*\*\d+\.?\d*)")
__add = re.compile(r"(-?\d+\.?\d*\+-\d+\.?\d*)|(-?\d+\.?\d*\+\d+\.?\d*)")
__sub = re.compile(r"(-?\d+\.?\d*--\d+\.?\d*)|(-?\d+\.?\d*-\d+\.?\d*)")
def division(self, value):
"""计算除法"""
exp = re.split(r'/', self.__div.search(value).group())
return value.replace(self.__div.search(value).group(), str(float(exp[0]) / float(exp[1])))
def multiplication(self, value):
"""计算乘法"""
exp = re.split(r'\*', self.__mul.search(value).group())
return value.replace(self.__mul.search(value).group(), str(float(exp[0]) * float(exp[1])))
def addition(self, value):
"""计算加法"""
exp = re.split(r'\+', self.__add.search(value).group())
return value.replace(self.__add.search(value).group(), str(float(exp[0]) + float(exp[1])))
def subtraction(self, value):
"""计算减法"""
exp = self.__sub.search(value).group()
if exp.startswith('-'):
exp = exp.replace('-', '+')
res = self.addition(exp).replace('+', '-')
else:
exp = re.split(r'-', exp)
res = str(float(exp[0]) - float(exp[1]))
return value.replace(self.__sub.search(value).group(), res)
class VerificationCode:
def __init__(self):
head = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36"
}
res_img = requests.get('验证码地址', headers=head)
with open('test.png', 'wb') as f:
f.write(res_img.content)
@staticmethod
def verification_code():
ocr = ddddocr.DdddOcr()
with open("test.png", 'rb') as f:
img_bytes = f.read()
res = ocr.classification(img_bytes)
print(res)
try:
if '+' in res:
result = RegularCalculation().addition(res)
elif '-' in res:
result = RegularCalculation().subtraction(res)
elif 'x' in res:
result = RegularCalculation().multiplication(res.replace('x', '*'))
else:
result = RegularCalculation().division(res)
except Exception as e:
result = '计算出错'
print(e)
print(result.split('.')[0])
if __name__ == '__main__':
test = VerificationCode()
test.verification_code()
|