Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
正在使用Python查找文件中的特定短语_Python_Regex - Fatal编程技术网

正在使用Python查找文件中的特定短语

正在使用Python查找文件中的特定短语,python,regex,Python,Regex,我知道论坛上也有一些类似的帖子,但是我需要一个文本文件的快速扫描。我必须通过1 GB文件运行500次检查,并打印出包含特定短语的行,以下是我的代码: import re with open('text.txt', 'r') as f: searchstrings = ('aaAa','bBbb') for line in f.readlines(): for word in searchstrings: word2 = ".*" + wor

我知道论坛上也有一些类似的帖子,但是我需要一个文本文件的快速扫描。我必须通过1 GB文件运行500次检查,并打印出包含特定短语的行,以下是我的代码:

import re
with open('text.txt', 'r') as f:
    searchstrings = ('aaAa','bBbb')
    for line in f.readlines():
        for word in searchstrings:
            word2 = ".*" + word + ".*"
            match = re.search(word2, line)
            if match:
                print word + "     " + line

我试图让它返回任何包含这些短语的行,所以即使该行是“bbjahdaaamm”,我也希望它返回,因为它包含aaaa。aaAa和bBbb只是示例,列表完全不同。

不要使用
f.readlines()
您将把整个1GB加载到内存中。一次读一本

相反,你应该:

searchstrings = ('aaAa','bBbb')
with open('text.txt', 'r') as f:
    for line in f:
        for word in searchstrings:
            if word.lower() in line.lower():
               print word + "     " + line

你是说无知的人吗?尝试重新搜索(word2,line,re.IGNORECASE)。

如果line.lower()中的word2.lower():而不是使用正则表达式,为什么不
导入re
变得不相关,然后:)