【发布时间】:2013-06-20 20:57:12
【问题描述】:
对于 Django 应用程序,如果我的数据库中有与匹配项相关的资源,我需要将字符串中所有出现的模式转换为链接。
现在,流程如下: - 我使用 re.sub 处理很长的文本字符串 - 当 re.sub 找到模式匹配时,它会运行一个函数来查找该模式是否与数据库中的条目匹配 - 如果有匹配项,则将链接包装在匹配项周围。
问题是有时对数据库有数百次点击。我想做的是对数据库进行一次批量查询。
那么:你能在 Python 中使用正则表达式进行批量查找和替换吗?
作为参考,这里是代码(对于好奇,我正在查找的模式是为了合法引用):
def add_linked_citations(text):
linked_text = re.sub(r'(?P<volume>[0-9]+[a-zA-Z]{0,3})\s+(?P<reporter>[A-Z][a-zA-Z0-9\.\s]{1,49}?)\s+(?P<page>[0-9]+[a-zA-Z]{0,3}))', create_citation_link, text)
return linked_text
def create_citation_link(match_object):
volume = None
reporter = None
page = None
if match_object.group("volume") not in [None, '']:
volume = match_object.group("volume")
if match_object.group("reporter") not in [None, '']:
reporter = match_object.group("reporter")
if match_object.group("page") not in [None, '']:
page = match_object.group("page")
if volume and reporter and page: # These should all be here...
# !!! Here's where I keep hitting the database
citations = Citation.objects.filter(volume=volume, reporter=reporter, page=page)
if citations.exists():
citation = citations[0]
document = citation.document
url = document.url()
return '<a href="%s">%s %s %s</a>' % (url, volume, reporter, page)
else:
return '%s %s %s' % (volume, reporter, page)
【问题讨论】:
-
你错过了一点。
reporter_code来自哪里? -
非常长的文本字符串有多长?
Citation.objects.count()千、百万是什么? -
对不起,reporter_code -- 为了这个问题,我试图简化我的代码,但忘记删除它。
-
关于你的第二个问题——目前大约是 300,000,尽管我预计它很快就会达到数百万。