gpt4 book ai didi

python - 如何将扫描文本中的数据导入 Django 模型

转载 作者:行者123 更新时间:2023-11-28 19:27:06 27 4
gpt4 key购买 nike

我有数百页的“测验”问题、多项选择以及相关的答案和解释。我正在尝试创建一个简单的 Django 应用程序来管理这些问题。我创建了一个简单但有效的 Python 解析器来将扫描的 OCR 页面解析为正确的对象。

我想要一个“实用程序”来让这个 Django 应用程序的管理员能够将 OCR 纸上的测验内容导入到相关的 Django 数据库表中。这将是一项罕见的任务,而且不一定适合包含在 Web UI 中。

我问过有关使用中间 JSON/YAML 固定装置的问题,并被告知更合适的方法是直接创建和保存我的模型 [1] 的实例。然后我尝试按照 [2] 和 [3] 建议的方式创建一个独立的脚本,但无法克服kwargs = {"app_label": model_module.__name__.split('.')[-2]}
IndexError:列表索引超出范围
错误。

我还遇到了关于创建自定义 django-admin.py/manage.py 命令的 [4]。这似乎是处理任务的逻辑上合适的方式;但是,我很想听听那些有更多经验和头脑的人的意见(我已经把我的都吃光了:)。

引用资料:

  1. Importing data from scanned text into Django as YAML fixture or SQL
  2. what is the simplest way to create a table use django db api ,and base on 'Standalone Django scripts'
  3. Standalone Scripts
  4. Writing custom django-admin commands

例子:

  • OCR 文本

Page 12 34. Hiedegger is a _____ . (a) philosopher (b) boozy beggar (c) both a and b (d) none of these 35. ...

  • Django 模型

    class Question(models.Model):
    text = models.TextField()
    class Choice(models.Model):
    question = models.ForeignKey(Question)
    order = models.IntegerField(default=1)
    text = models.TextField()
  • 目标,像这样...

    q = Question.objects.create(text="Hiedegger is a _____ .")
    q.save()
    c = Choice(text="philosopher", order=1, question=q.pk)
    c.save()

最佳答案

这是我想出的工作版本。肮脏,但有效。 @akonsu 和@Ivan Kharlamov 都提供了帮助。谢谢...

import os, re, Levenshtein as lev, codecs
from SimpleQuiz.quiz.models import Choice, Question
from django.core.management.base import BaseCommand, CommandError
import optparse

class Command(BaseCommand):
args = '--datapath=/path/to/text/data/'
can_import_settings = True
help = 'Imports scanned text into Questions and Choices'
option_list = BaseCommand.option_list + (
optparse.make_option('--datapath', action='store', type='string',
dest='datapath',
help='Path to OCRd text files to be parsed.'),
)
requires_model_validation = True
# Parser REs
BACKUP_RE = re.compile(r'\~$|bak$|back$|backup$')
QUEST_RE = re.compile(r'^[0-9]{1,3}[.][ ]')
CHOICE_RE = re.compile(r'^[a-e][.][ ]')

def handle(self, *args, **options):
# get the data path
try:
os.path.exists(options['datapath'])
except Exception as e:
raise CommandError("None or invalid path provided: %s" % e.message)
self.datapath = os.path.expanduser(options['datapath'])

# generate list of text strings from lines in target files
self.data_lines = []
for fn in os.listdir(os.path.join(self.datapath, 'questions/')):
if self.BACKUP_RE.search(fn):
self.stderr.write("Skipping backup: %s\n" % (fn))
else:
for line in codecs.open(os.path.join(self.datapath, 'questions/', fn), 'r', encoding='latin-1'):
if not self.is_boilerplate(line):
if not line.strip() == '':
self.data_lines.append(line)

#-----------------------------------------------------------------------
#--------------------- Parse the text lines and create Questions/Choices
#-----------------------------------------------------------------------
cur_quest = None
cur_choice = None
cur_is_quest = False
questions = {}
choices = {}
for line in self.data_lines:
if self.is_question(line):
[n, txt] = line.split('.', 1)
qtext = txt.rstrip() + " "
q = Question.objects.create(text=qtext)
q.save()
cur_quest = q.pk
questions[cur_quest] = q
cur_is_quest = True
elif self.is_choice(line):
[n, txt] = line.split('.', 1)
num = self.char2dig(n)
ctext = txt.rstrip() + " "
c = Choice.objects.create(text=ctext, order=num, question=questions[cur_quest])
c.save()
cur_choice = c.pk
choices[cur_choice] = c
cur_is_quest = False
else:
if cur_is_quest:
questions[cur_quest].text += line.rstrip() + " "
questions[cur_quest].save()
else:
choices[cur_choice].text += line.rstrip() + " "
choices[cur_choice].save()
self.stdout.write("----- FINISHED -----\n")
return None

def is_question(self, arg_str):
if self.QUEST_RE.search(arg_str):
return True
else:
return False

def is_choice(self, arg_str):
if self.CHOICE_RE.search(arg_str):
return True
else:
return False

def char2dig(self, x):
if x == 'a':
return 1
if x == 'b':
return 2
if x == 'c':
return 3
if x == 'd':
return 4
if x == 'e':
return 5

def is_boilerplate(self, arg_str):
boilerplate = [u'MFT PRACTICE EXAMINATIONS',
u'BERKELEY TRAINING ASSOCIATES ' + u'\u00A9' + u' 2009',
u'BERKELEY TRAINING ASSOCIATES',
u'MARRIAGE AND FAMILY THERAPY',
u'PRACTICE EXAMINATION 41',
u'Page 0', u'Page 1', u'Page 2', u'Page 3', u'Page 4',
u'Page 5', u'Page 6', u'Page 7', u'Page 8', u'Page 9',
]
for bp in boilerplate:
if lev.distance(bp.encode('utf-8'), arg_str.encode('utf-8')) < 4:
return True
return False

关于python - 如何将扫描文本中的数据导入 Django 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7844630/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com