【发布时间】:2015-02-06 14:26:04
【问题描述】:
现在我有两个大文件,pattern file和log file,每个都有超过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
我的任务是从特定回复中获取所有评论,以分析用户对这些给定回复的情绪。所以这是我一步一步做的:
- 挑选所有模式和日志,它们都使用正则表达式,
- 然后将它们与字符串比较操作一起匹配。
我需要优化代码,目前需要 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()。我不知道如何减少它。
【问题讨论】:
-
所以您正试图对 300,000 行执行 300,000 次单独搜索?这听起来像是 10^11 左右的操作,这确实需要很长时间。也许你需要重新考虑你想要达到的目标。但如果你把它充实一点,它可能会成为一个有趣的问题。您能否与我们分享更多有关要搜索的特定模式和文本的信息?为什么需要这么多模式?这个项目的总体目标是什么?
-
你不能只迭代一次日志文件并创建一个大字典
{replyStr: [CommentOfReply, ...]}吗?然后迭代模式文件并一次获取所有回复的 cmets。 -
@stanleyerror 如果您提供两个文件的一小段代表性摘录(可能大约十行),那么如果需要,我可能会编写一些示例代码来帮助您入门。
-
@tobias_k 哈哈,你真好。好吧,我应该独立解决,因为这是我的任务。无论如何,您的解决方案很有帮助。
-
你自己完成的愿望令人钦佩。不要忘记,一旦您开发了解决方案,您可以根据需要回答自己的问题。
标签: python regex optimization profile