1.前言
使用正则表达式对文本进行处理时,一般需要在匹配前使用re.compile()进行优化,它将正则表达式转化为对象。re.compile()起到的是一个预编译的效果,在进行匹配前,先把匹配规则进行预先编译,生成正则对象。re.search(pattern, string)的调用方式就转换为 pattern.search(string)的调用方式,多次调用一个正则表达式就重复利用这个正则对象,避免了在每次匹配时都进行编译,可以节省大量时间。
2.使用
2-1. re.compile()与findall()结合
#使用预编译前
import re
pattern = re.compile(r'/item/(.*?)[?#]')
category = re.findall(pattern, href)
#使用预编译后
import re
pattern = re.compile(r'/item/(.*?)[?#]')
category = pattern.findall(href)
2-2. re.compile()与findall()结合
#使用预编译后
import re
href = 'https://baike.baidu.com/item/开封/122642?fromModule=lemma_search-box'
pattern = re.compile(r'/item/(.*?)[?#]')
category = pattern.search(href)
2-3. re.compile()与sub()结合
#使用预编译前
import re
temp_title = [re.sub('\s', '', item) for item in basicInfo_keys]
#使用预编译后
req_s = re.compile('\s')
temp_title = [req_s.sub('', item) for item in basicInfo_keys]
3.总结
使用re.compile()对正则表达式提前进行编译,可以提高数据处理效率,注意要将经过re.compile()生成的对象,写在程序开端。