两天肝出刷题小程序---AI识图生诗词文案(欢迎互踩)后端django

有个朋友要考2024年上海三类人员安管考试B证,他手里是一个word试题文档。需要打印出来在背,很麻烦。但是由于是太专业太新的试题,在网上没有类似的小程序。所以我利用两天时间在现有小程序(AI识图生诗词文案)基础上增加了一个刷题页面。

先给自己的小程序曝光一下,欢迎各位大佬光临!扫码或搜索AI识图生诗词文案

首先将word转为json文件,word试题里面的答案是绿色标记的,题库大约2000道题,所以我写了个脚本,识别答案后将word转为json

from docx import Document
import json
from docx.oxml.ns import qn
import re

def clean_text(text):
    # 使用正则表达式替换一个或多个空白字符为一个空格
    text = re.sub(r'\s+', '', text)  # 注意:这里的更改使空白字符替换为一个空格,而不是完全去除
    # 去除字符串两端的空格
    text = text.strip()
    return text

def has_shading(cell):
    # 检查单元格是否有特定的颜色填充(在这个例子中是绿色的 '92D050')
    try:
        tc_pr = cell._tc.get_or_add_tcPr()
        if tc_pr is not None:
            shd = tc_pr.first_child_found_in("w:shd")
            if shd is not None:
                fill = shd.get(qn('w:fill'))
                # 如果填充颜色是 '92D050',则认为这是一个答案单元格
                return fill == '92D050'
    except AttributeError as e:
        print("Error:", e)
    return False

# 加载Word文档
doc = Document('E:\\DJ\\AIwenanquan\\common\\danxuan.docx')

questions = []
question_id = 1  # 初始化问题ID

# 遍历文档中的所有表格
for table in doc.tables:
    for row in table.rows:
        current_question = {}
        cells = row.cells
        current_question['id'] = question_id  # 使用新的问题ID
        current_question['type'] = clean_text(cells[1].text)
        current_question['question'] = clean_text(cells[2].text)
        options = [clean_text(cells[i].text) for i in range(3, len(cells))]
        current_question['options'] = [option for option in options if option]  # 排除空字符串
        # 识别并提取有颜色填充的单元格作为答案
        answers = [options[i-3] for i in range(3, len(cells)) if has_shading(cells[i])]
        current_question['answer'] = answers  # 假设可能有多个正确答案
        questions.append(current_question)
        question_id += 1  # 递增问题ID

# 将问题列表直接转换为JSON格式,而不是嵌套在另一个字典中
json_output = json.dumps(questions, ensure_ascii=False, indent=2)
# 打印或保存JSON数据
print(json_output)
# 保存
with open('E:\\DJ\\AIwenanquan\\common\\danxuan.json', 'w', encoding='utf-8') as f:
    f.write(json_output)

有了json文件就很容易导入mysql数据库中
 

import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AIwenanquan.settings')
django.setup()

import json
from shuati.models import tfQuestion


# 加载JSON数据
with open('panduan.json', 'r', encoding='utf-8') as file:
    questions = json.load(file)
# 导入数据到MySQL
for q in questions:
    question = tfQuestion(
        id=q["id"],
        type=q["type"],
        question=q["question"],
        options=q["options"],
        answer=q["answer"],
    )
    question.save()

以上基础工作就算做完了,下面可以写django后端了。

下面是models

#models.py

class multipleQuestion( BaseModel):
    type = models.CharField(max_length=50, help_text='试题类型', verbose_name='试题类型', default=None,
                                  null=True)
    question = models.CharField(max_length=1000, help_text='试题', verbose_name='试题', default=None,
                                  null=True)
    options = models.CharField(max_length=1000, help_text='选项', verbose_name='选项', default=None,
                                  null=True)
    answer = models.CharField(max_length=1000, help_text='答案', verbose_name='答案', default=None,
                                  null=True)

    class Meta:
        db_table = 'multiplequestion'
        verbose_name = '多选题'
        #后台显示的名字
        verbose_name_plural = verbose_name

下面是views:

class multipleQuestionView(APIView):
    queryset = multipleQuestion.objects.all()
    serializer_class = multipleQuestionSerializer
    permission_classes = [IsAuthenticated, multipleQuestionPermission]
    def post(self, request, *args, **kwargs):
        questionid = request.data.get('questionid')
        # 检查questionid是否提供
        if questionid is None:
            return Response({'error': '请提供题目id'})
        try:
        # 使用questionid从数据库中检索题目
            question = multipleQuestion.objects.get(id=questionid)
        except multipleQuestion.DoesNotExist:
            return Response({'error': 'question does not exist'})
            # 获取数据库中总共有多少道题目
        total_questions = multipleQuestion.objects.count()

        serializer = multipleQuestionSerializer(question)
            # 将题目总数添加到返回的数据中
        data = serializer.data
        data['total_questions'] = total_questions
        return Response({'code': 200, **data})

url:
 

# 获取多选题
    url(r'getmultiplequestions/', multipleQuestionView.as_view()),

以上一套连招下来就可以通过题目的id访问题库了。

下一篇写前端代码。

  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值