快速检查字符串是否在一个巨大的文本文件中的方法

时间:2017-01-07 11:12:52

标签: python file text

我正在寻找一种简单的方法来检查列表中的所有字符串是否都在一个巨大的文本文件中(> 35.000字)。

self.vierkant = ['BIT', 'ICE', 'TEN']


def geldig(self, file):
    self.file = file
    file = open(self.file, 'r')
    line = file.readline()
    self.file = ''

    while line:
        line = line.strip('\n')
        self.file += line
        line = file.readline()

    return len([woord for woord in self.vierkant if woord.lower() not in self.file]) == 0

我只是将文本文件复制到self.file中,然后检查self.vierkant中的所有单词是否都在self.file中。

主要问题是读取文本文件需要很长时间。 是否有更容易/更快的方法来做到这一点?

2 个答案:

答案 0 :(得分:2)

您可以使用file.read()阅读文件的全部内容,而不是重复调用readline()并连接结果:

with open(self.file) as f:
    self.file = f.read()

如果您需要检查很多单词,您还可以从文件的内容中构建set以进行O(1)包含检查。

答案 1 :(得分:0)

with open('a.txt') as f:
    s = set(f.read().splitlines())  # splitlines will remove the '\n' in the end and return a list of line.
for line in test_lines:
    line in s  # O(1) check if the the line in the line-set
相关问题