【发布时间】:2010-09-09 01:54:24
【问题描述】:
每次导入包含大量静态正则表达式的 python 文件时,都会花费 cpu 周期将字符串编译到内存中的代表性状态机中。
a = re.compile("a.*b")
b = re.compile("c.*d")
...
问题:是否可以将这些正则表达式以预编译的方式存储在磁盘上的缓存中,以避免每次导入时都必须执行正则表达式编译?
pickling 对象只是执行以下操作,无论如何都会导致编译发生:
>>> import pickle
>>> import re
>>> x = re.compile(".*")
>>> pickle.dumps(x)
"cre\n_compile\np0\n(S'.*'\np1\nI0\ntp2\nRp3\n."
并且re 对象是不可编组的:
>>> import marshal
>>> import re
>>> x = re.compile(".*")
>>> marshal.dumps(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: unmarshallable object
【问题讨论】:
-
可悲的是,我的应用程序(900 个正则表达式和计数)也有这个问题。不幸的是,我在这个帖子中没有看到任何解决方案。