Python 3:使用 REGEX 搜索大型文本文件 [英] Python 3: Searching A Large Text File With REGEX

查看:39
本文介绍了Python 3:使用 REGEX 搜索大型文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用正则表达式搜索一个大文本文件并设置以下代码:

I wish to search a large text file with regex and have set-up the following code:

import re

regex = input("REGEX: ")

SearchFunction = re.compile(regex)

f = open('data','r', encoding='utf-8')

result = re.search(SearchFunction, f)

print(result.groups())

f.close()

当然,这不起作用,因为 re.search 的第二个参数应该是字符串或缓冲区.但是,我无法将所有文本文件插入到一个字符串中,因为它太长(这意味着它会花费很长时间).什么是替代方案?

Of course, this doesn't work because the second argument for re.search should be a string or buffer. However, I cannot insert all of my text file into a string as it is too long (meaning that it would take forever). What is the alternative?

推荐答案

检查每一行的模式是否匹配.这不会将整个文件加载到内存中:

You check if the pattern matches for each line. This won't load the entire file to the memory:

for line in f:
    result = re.search(SearchFunction, line)

这篇关于Python 3:使用 REGEX 搜索大型文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆