Skip to main content
 首页 » 编程设计

python之正则表达式性能 Python

2024年08月21日32kenshinobiy

我正在编写一个 Python 脚本,它传递超过 20GB 的新闻文章数据。对于作为“日期”的每一行(每 100 行左右一次),我需要检查该文章的标题是否为财务。标题的形式是:

SOME BIG NEWS HAPPENED TO CISCO 

我的代码遍历标准普尔 500 指数中的每个公司名称(我已将其缓存在 set 中),并尝试查看名称是否匹配。

line = "SOME BIG NEWS HAPPENED TO CISCO" 
for company in company_names: 
    pattern = re.compile("(\\b" + company_name + "\\b)", flags=re.IGNORECASE) 
    if re.search(pattern, line): 
        do_something() 

我将仅仅 100,000 行复制到一个单独的文件中以测试我的程序,这花费了 347 秒。以这种速度,它不会在一周以上的时间内通过我的所有数据。

我想弄清楚为什么循环遍历我的文件可能需要这么长时间。问题是 Python 无法缓存所有已编译的 DFA,而是每次遇到新文章时都需要构造 ~500?

还是我当前的正则表达式存在其他问题导致执行时间如此之长?

如有任何帮助,我们将不胜感激。

请您参考如下方法:

您可以尝试在字典中保存预编译的模式。像这样的东西:

companies=('Cisco', 'Apple', 'IBM', 'GE') 
patterns={co:re.compile("(\\b" + co + "\\b)", flags=re.IGNORECASE) for co in companies} 
line = "SOME BIG NEWS HAPPENED TO CISCO" 
for co, pat in patterns.items(): 
    if re.search(pat, line): 
        print "'{}' found in: '{}'".format(co, line) 

或者,您可以尝试 Python 的字符串方法:

words=line.lower().split()       
for co in [e.lower() for e in companies]: 
    if co in words: 
       print "'{}' found in: '{}'".format(co, line)     

请注意,在行上执行 [e.strip(',.!:;') for e in line.lower().split()] 几乎等同于使用单词边界并且在正则表达式中不区分大小写。 (或者使用 TigerhawkT3 的 ''.join(filter(str.isalpha, line.lower())).split(): do_something())

您还可以使用 set intersection获取常用词:

>>> line2="Apple acquires Cisco: Generally a good thing" 
>>> set(e.lower() for e in companies) & set(e.strip(',.!:;') for e in line2.lower().split()) 
set(['cisco', 'apple'])