算式样式:

  • 分数 2/4+2/4=?
  • 分数+小数 4/8×7.2=?
  • 括号 (4/5-7/15)×15=?

处理逻辑:

  1. 替换括号和乘除号,区分等式
  2. 依次替换分数为Fraction形式
  3. 依次替换小数位Fraction形式
  4. 调用eval + Fraction,输出最终分数

结果:

源码如下:

#!/usr/bin/env python
# -- coding: utf-8 --
"""
Copyright (c) 2021. All rights reserved.
Created by C. L. Wang on 13.8.21
"""import collections
import copy
import os
import re
from fractions import Fractionfrom myutils.project_utils import read_excel_file, write_list_to_excel, create_file
from root_dir import DATA_DIRclass NumbersCalculator(object):def __init__(self):self.xlsx_path = os.path.join(DATA_DIR, '口算分数计算2-20210813.xlsx')self.out_xlsx_path = os.path.join(DATA_DIR, '口算分数计算2-20210813.out.xlsx')create_file(self.out_xlsx_path)@staticmethoddef repalce_one_by_one(data_str, r_list, func_x):"""逐个替换"""def replace_nth(s, sub, repl, n):"""替换第n个"""find = s.find(sub)# If find is not -1 we have found at least one match for the substringi = find != -1# loop util we find the nth or we find no matchwhile find != -1 and i != n:# find + 1 means we start searching from after the last matchfind = s.find(sub, find + 1)i += 1# If i is equal to n we found nth match so replaceif i == n:return s[:find] + repl + s[find + len(sub):]return sdef find_nth(haystack, needle, n):"""找到第n个"""start = haystack.find(needle)while start >= 0 and n > 1:start = haystack.find(needle, start + len(needle))n -= 1return startres_s = copy.copy(data_str)b_list = len(data_str) * [True]  # 判断是否已经处理time_dict = collections.defaultdict(int)  # 出现次数for sub_str in r_list:while True:n_time = time_dict[sub_str]  # 出现第几次x = find_nth(data_str, sub_str, n_time + 1)if x == -1:breakif b_list[x]:b_list[x:x+len(sub_str)] = [False]*len(sub_str)n_time = time_dict[sub_str] + 1# 自定义replaceres_s = replace_nth(res_s, sub_str, func_x(sub_str), n_time)breakelse:time_dict[sub_str] += 1return res_s@staticmethoddef process_data(data):"""计算等式"""# 第1部分,拆分等号question = data.replace(' ', '').replace('(', '(').replace(')', ')')question = question.replace('×', '*').replace('÷', '/')left = question.strip().split('=')[0]right = question.strip().split('=')[-1]print('[Info] left: {}, right: {}'.format(left, right))# 第2部分,替换分数pattern = re.compile(r'[0-9]+/[0-9]+')frac_list = pattern.findall(left)frac_list = sorted(list(frac_list), key=len, reverse=True)print('[Info] frac_list: {}'.format(frac_list))def func1_x(s_str):return 'Fraction(\'{}\')'.format(s_str)left = NumbersCalculator.repalce_one_by_one(left, frac_list, func1_x)# 第3部分,替换小数pattern2 = re.compile(r'[0-9]+\.[0-9]+')frac2_list = pattern2.findall(left)frac2_list = sorted(list(frac2_list), key=len, reverse=True)print('[Info] frac2_list: {}'.format(frac2_list))def func2_x(s_str):return 'Fraction(\'{}\')'.format(Fraction(s_str))left = NumbersCalculator.repalce_one_by_one(left, frac2_list, func2_x)print('[Info] left: {}'.format(left))x_dict = {"Fraction": Fraction}res = eval(left, x_dict)print("[Info] res: {}".format(res))print('-' * 100)return resdef process(self):print("[Info] 处理文件: {}".format(self.xlsx_path))data_lines = read_excel_file(self.xlsx_path)print("[Info] 样本数: {}".format(len(data_lines)))title_list = ["转换后题干", "结果"]res_list = []for data_idx, data_line in enumerate(data_lines):if data_idx == 0:continuedata = data_line[0]print('[Info] data_idx: {}, data: {}'.format(data_idx, data))res = NumbersCalculator.process_data(data)res_list.append([data, str(res)])write_list_to_excel(self.out_xlsx_path, title_list, res_list)print("[Info] 处理完成: {}".format(self.out_xlsx_path))def test(self):data = "2/4+2/4=?"  # 测试self.process_data(data)def main():nc = NumbersCalculator()# nc.test()nc.process()if __name__ == '__main__':main()

Python - 计算复杂算式和分式相关推荐

  1. python用户输入算式并计算_Python基础学习之计算和算式

    今天小编要跟大家分享的文章是关于Python基础学习之计算和算式.正在学习Python相关知识的小伙伴们来和小编一起看一看吧,希望能够对大家有所帮助! Python 具有执行计算的能力. 直接在 Py ...

  2. python -- 计算 平方、乘方、平方根_从零开始学习PYTHON3讲义(二)把Python当做计算器...

    <从零开始PYTHON3>第二讲 上一讲我们说过了如何启动Python IDLE集成开发学习环境,macOS/Linux都可以在命令行执行idle3.Windows则从开始菜单中去寻找ID ...

  3. 使用OpenCV和Python计算图像的“彩色度”

    使用OpenCV和Python计算图像"彩色度" 1. 效果图 2. 炫彩度量方法是什么? 3. 源代码 参考 你是否尝试过计算每个图像的炫彩值,并根据炫彩值对自己的图像数据集进行 ...

  4. Python计算训练数据集(测试集)中某个分类变量阴性(阳性)标签样本的不同水平(level)或者分类值的统计个数以及比例

    Python计算训练数据集(测试集)中某个分类变量阴性(阳性)标签样本的不同水平(level)或者分类值的统计个数以及比例 目录

  5. Python计算两个numpy数组的交集(Intersection)实战:两个输入数组的交集并排序、获取交集元素及其索引、如果输入数组不是一维的,它们将被展平(flatten),然后计算交集

    Python计算两个numpy数组的交集(Intersection)实战:两个输入数组的交集并排序.获取交集元素及其索引.如果输入数组不是一维的,它们将被展平(flatten),然后计算交集 目录

  6. Python使用datetime中的timedelta模块实现时间增减:python计算100天后是哪年那月那日?

    Python使用datetime中的timedelta模块实现时间增减:python计算100天后是哪年那月那日? 目录

  7. python计算特征的统计值并文本输出

    python计算特征的统计值并文本输出 # 输出统计分位数 df.describe(percentiles=[0.05, 0.25, 0.5, 0.75, 0.95]) featname:A => ...

  8. python计算特征与目标的相关性并可视化

    python计算特征与目标的相关性并可视化 pandas计算相关性 # 相关性 tips.corr() Out[2]: total_bill tip size total_bill 1.000000 ...

  9. python计算时间差

    python计算时间差 # 使用datetime 和 timedelta import datetime old_time = datetime.datetime.now() print(old_ti ...

最新文章

  1. windows下安装mysql8.0压缩版
  2. numpy中的tile函数
  3. [ATC 17] StreamBox: 面向多核机器上的针对Records的无序到达的实时流处理系统
  4. 使用IDA 进行远程调试
  5. 是什么造就了伟大的程序员?
  6. percona 5.7.11root初始密码设置
  7. [bzoj1969] [Ahoi2005]LANE 航线规划
  8. 列标题 如何删除gridcontrol_Excel如何制作工资条?
  9. linux给文件备份,Linux文件备份
  10. AUTOCAD——超级填充
  11. 51/STC12单片机SCON,PCON,TMOD寄存器定义及功能
  12. 如何批量将 PPT 幻灯片文档转换为 XPS 格式
  13. python风变编程和扇贝编程_想学习phython ,纠结是扇贝编程还是风变编程?
  14. 龙芯电脑的详细资料,支持国货的请进来!
  15. DataCastle租金预测数据竞赛个人总结
  16. Available platform plugins are: xcb, eglfs, linuxfb, minimal, minimalegl, of
  17. Vue3.0 directive的使用说明
  18. 想要学习丙烯画,这些地方要注意了~
  19. 在localhost和本地服务器(127.0.0.1)中使用ajax发起post请求遇到的问题。
  20. Git的基本使用(用户初始化配置、新建代码库、把文件提交到缓存区、把文件提交到本地仓库等)

热门文章

  1. 破甲两千六 Spring Cloud 教程(三):添加Spring Cloud 的 Netflix Eureka 插件,实现服务端、客户端的发现与注册
  2. 迅雷无法下载的解决方法
  3. easywechat5发送模板消息
  4. 【数据库】数据库管理系统(Database Management Systems)
  5. ORA-00257: archiver error. Connect internal only, until freed 错误解决方案
  6. 喜马拉雅忙着上市,蜻蜓FM忙着融资
  7. 灰度变换-分段线性函数
  8. 2014年网研上机题目
  9. 洛咕 P2465 [SDOI2008]山贼集团
  10. windows卸载夸克网盘没有卸载干净