Skip to main content
 首页 » 编程设计

python之优化python对大文件的regex和文件读取操作

2024年10月25日9grandyang

现在我有两个大文件,模式文件和日志文件,每个文件都有超过300,000行。模式文件是这样的格式:

Line 1 : <ID>   <Dialog1>    <ReplyStr>    <Dialog2>     
// the ReplyStr is needed as a pattern 

日志文件是这样的格式:

Line 1 : <LogData>    <ReplyStr>    <CommentOfReply>    
// get all CommentOfReply, whose ReplyStr is from the pattern file 

我的任务是从特定回复中获取所有评论,以分析用户对这些给定回复的情绪。所以这是我一步一步做的:

  1. 挑选出所有模式和日志,它们都使用正则表达式,
  2. 然后通过字符串比较操作将它们匹配在一起。

我需要优化代码,目前需要 8 个小时才能完成。

配置文件如下(在前 10 个循环中使用 cProfile):

   ncalls  tottime  percall  cumtime  percall filename:lineno(function) 
        1    0.000    0.000   19.345   19.345 <string>:1(<module>) 
        1    7.275    7.275   19.345   19.345 get_candidate2.py:12(foo) 
  3331494    2.239    0.000   10.772    0.000 re.py:139(search) 
  3331496    4.314    0.000    5.293    0.000 re.py:226(_compile) 
      7/2    0.000    0.000    0.000    0.000 sre_compile.py:32(_compile) 
                            ...... 
  3331507    0.632    0.000    0.632    0.000 {method 'get' of 'dict' objects} 
  3331260    0.560    0.000    0.560    0.000 {method 'group' of '_sre.SRE_Match' objects} 
        2    0.000    0.000    0.000    0.000 {method 'items' of 'dict' objects} 
        2    0.000    0.000    0.000    0.000 {method 'remove' of 'list' objects} 
  3331494    3.241    0.000    3.241    0.000 {method 'search' of '_sre.SRE_Pattern' objects} 
        9    0.000    0.000    0.000    0.000 {method 'split' of 'str' objects} 
  6662529    0.737    0.000    0.737    0.000 {method 'strip' of 'str' objects} 

从配置文件来看,似乎所有耗时都来自re.search()。我不知道如何减少它。

请您参考如下方法:

感谢@MikeSatteson 和@tobias_k 的帮助,我弄明白了。

要从日志文件中找出与给定回复字符串(来自模式文件)相对应的所有评论字符串,解决方案是:

  1. 需要一个字典,其键为回复字符串,值为评论字符串列表。
  2. 从模式文件中取出所有的回复字符串,作为字典的键集。
  3. 从日志文件中取出所有的回复-评论对,如果字典的键集中包含回复,则将评论追加到评论列表中。

代码如下:

my_dict = {} 
with open('pattern file', 'r') as pattern_file: 
    for line in pattern_file: 
        reply = get_reply(line) 
        my_dict[reply] = list()      
 
with open('log file', 'r') as log_file: 
    for line in log_file: 
        pair = get_comment_reply_pair(line) 
        reply = pair.reply 
        comment  = pair.comment 
        if reply in my_dict: 
            l = my_dict[reply] 
            l.append(comment)