如何将扫描文本数据导入Django模型
我有几百页的“测验”题目,包括选择题选项和相关的答案及解释。我想创建一个简单的Django应用来管理这些问题。我已经写了一个简单有效的Python解析器,可以把扫描的、经过OCR处理的页面转换成合适的对象。
我想要一个“工具”,让这个Django应用的管理员能够把OCR处理过的纸质测验内容导入到相关的Django数据库表中。这是一个不常见的任务,也不一定适合放在网页界面上操作。
我曾经询问过使用中间的JSON/YAML文件来导入数据,得到的建议是直接创建并保存我的模型实例会更合适。我尝试按照建议创建一个独立的脚本,但遇到了一个错误,提示是kwargs = {"app_label": model_module.__name__.split('.')[-2]} IndexError: list index out of range
。
我还发现了关于创建自定义的django-admin.py/manage.py命令的内容。这似乎是处理这个任务的一个合理方法;不过,我很想听听那些经验丰富的人士的看法(我已经把我的脑细胞都用光了 :)。
参考资料:
示例:
- OCR处理的文本
第12页 34. 海德格尔是一个_____。(a)哲学家(b)醉酒乞丐(c)两者都是(d)以上都不是 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()
2 个回答
我尝试创建一个独立的脚本,按照[2]和[3]的建议,但遇到了一个问题,出现了kwargs = {"app_label": model_module.name.split('.')[-2]}的IndexError: list index out of range错误。
我也遇到了同样的列表索引错误。这个错误是因为我在脚本中导入模型的方式不对。我以前是这样做的:
from models import Table1, Table2
然后我意识到这个Python脚本并不是应用程序的一部分,所以我把导入方式改成了:
from myapp.models import Table1, Table2
我的Python脚本是通过以下的shell脚本启动的:
export DJANGO_SETTINGS_MODULE=settings
export PYTHONPATH=/path/to/my/site
python myscript.py "$@"
这是我想出来的可用版本。虽然有点乱,但有效。@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