简体   繁体   English

可以预编译Python中的正则表达式,保存到文件中,然后从文件中重新加载吗?

[英]Can you pre-compile regular expressions in Python, save them to a file, and then reload them from the file?

I have an application that loads a large table of regular expressions from an Excel file, compiles them, and then uses them to perform its function.我有一个应用程序,它从 Excel 文件加载一个大的正则表达式表,编译它们,然后使用它们来执行它的 function。 It takes about 2 minutes for Python to compile the regular expressions, which will increase as I add more expressions to the Excel file. Python 编译正则表达式大约需要 2 分钟,随着我向 Excel 文件中添加更多表达式,这将增加。 The Excel file does not change often, so I would like to avoid the two-minute+ startup time whenever the Excel file has not changed. Excel 文件不经常更改,所以我想避免每当 Excel 文件没有更改时的两分钟以上的启动时间。

Is there a way to cache the compiled regular expressions to a file that I can load when the Excel file hasn't changed?当 Excel 文件未更改时,有没有办法将编译的正则表达式缓存到我可以加载的文件中?

You can store the compiled regular expressions in pickle files:您可以将编译的正则表达式存储在 pickle 文件中:

import re
import pickle

r1 = re.compile('\d\d\d')

with open('tmp', 'wb') as fh:
    pickle.dump(r1, fh)


with open('tmp', 'rb') as fh:
    r2 = pickle.load(fh)

    print(r2.match('673'))

<re.Match object; <re.Match object; span=(0, 3), match='673'>跨度=(0, 3),匹配='673'>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我可以预编译 python 脚本吗? - Can I pre-compile a python script? 从XML文件中读取正则表达式,将其存储到列表列表中,然后使用它们 - Reading regular expressions from a XML file, store them into a list of list and afterwards use them 如何从 a.txt 文件中读取值并将它们保存到 python 中的不同变量中并访问它们? - How can I read values from a .txt-file and save them into different variables in python and get access to them? 如何从 txt 文件中获取特定列并使用 python 将它们保存到新文件中 - How can I get specific columns form txt file and save them to new file using python python 中用于搜索文件的正则表达式 - regular expressions in python for searching file 将正则表达式写入文件Python - Writing Regular Expressions to a file Python 如何将所有 txt 文件从目录转换为 csv(创建和写入文件)并使用 Python 保存它们? - How to convert all the txt file from a dir to csv's (creating and writing to file )and save them using Python? 我如何在python中使用split函数拆分文本部分并将其保存到其他文件? - How can i use split function in python to split parts of text and save them to a different file? 是否可以预编译(预构建/预安装)Python C / C ++扩展? - Is it possible to pre-compile (pre-build/pre-install) a Python C/C++ extension? 如何生成多个文件路径并保存到一个excel和python - How to generate multiple file paths and save them into a excel with python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM