python - 优化python中大文件的正则表达式和文件读取操作

标签 python regex optimization profile

现在我有两个大文件,模式文件日志文件,每个文件都有超过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)

关于python - 优化python中大文件的正则表达式和文件读取操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28367914/

相关文章:

python - 在 blobstore 中更新和保存现有的 blob/文件?

python - 使用正则表达式清理数据框列值

javascript - 将两个正则表达式合并为一个

php - 使用正则表达式从字符串中提取模式

c - 如果更喜欢使用 -ffast-math,则 double 的良好标记值

iphone - iPhone 上的编译器优化和 UIView 框架

c++ - 您如何找到程序中最不优化的部分?

python - 优化函数评估缓存部分结果

python - 为 Python 应用程序设置 Mysql 容器的 Docker

python - 有没有办法更新一个包,并递归地更新它使用的所有包?