比较文本文件内容的最快方法

fastest way to compare text file content

我有一个问题可以帮助简化我的编程。 所以我有这个文件 text.txt,我想在其中查看它并将其与单词列表 words 进行比较,每次找到单词时它都会将 1 添加到一个整数。

words = ['the', 'or', 'and', 'can', 'help', 'it', 'one', 'two']
ints = []
with open('text.txt') as file:
    for line in file:
        for part in line.split():
            for word in words:
                if word in part:
                    ints.append(1)

我只是想知道是否有更快的方法来做到这一点?文本文件可能会更大,单词列表也会更大。

您可以使用 set.intersection 找到集合和列表之间的交集,以便更有效地将您的单词放在 set 中并执行 :

words={'the','or','and','can','help','it','one','two'}
ints=[]
with open('text.txt') as f:
    for line in f:
        for _ in range(len(words.intersection(line.split()))):
              ints.append(1)

请注意,上述解决方案基于您将 1 添加到列表的代码。如果您想找到最终计数,可以在 sum :

中使用生成器表达式
words={'the','or','and','can','help','it','one','two'}
with open('text.txt') as f:
    sum(len(words.intersection(line.split())) for line in f)

您可以将 words 转换为 set,这样查找速度会更快。这应该会给您的程序带来良好的性能提升,因为在列表中查找值必须一次遍历列表一个元素(O(n) 运行时复杂度),但是当您将列表转换为集合时,运行时复杂度将降低到 O(1)(常数时间)。因为集合使用散列来查找元素。

words = {'the', 'or', 'and', 'can', 'help', 'it', 'one', 'two'}

然后每当有匹配的时候,就可以用sum函数这样统计

with open('text.txt') as file:
    print(sum(part in words for line in file for part in line.split()))

布尔值及其等价整数

在 Python 中,对于 FalseTrue,布尔表达式的结果将分别等于 01

>>> True == 1
True
>>> False == 0
True
>>> int(True)
1
>>> int(False)
0
>>> sum([True, True, True])
3
>>> sum([True, False, True])
2

因此,无论何时检查 part in words,结果都将是 01,我们 sum 所有这些值。


上面看到的代码在功能上等同于

result = 0
with open('text.txt') as file:
    for line in file:
        for part in line.split():
            if part in words:
                 result += 1

注意: 如果你真的想在有匹配项的列表中得到 1,那么你可以简单地将生成器表达式转换为 sum 到列表理解,像这样

with open('text.txt') as file:
    print([int(part in words) for line in file for part in line.split()])

词频

如果你真的想在 words 中找到单个单词的频率,那么你可以像这样使用 collections.Counter

from collections import Counter
with open('text.txt') as file:
    c = Counter(part for line in file for part in line.split() if part in words)

这将在内部计算 words 中每个单词在文件中出现的次数。


根据,你可以有一个字典,你可以在其中存储得分为正的积极词和得分为负的消极词,并像这样计算它们

words = {'happy': 1, 'good': 1, 'great': 1, 'no': -1, 'hate': -1}
with open('text.txt') as file:
    print(sum(words.get(part, 0) for line in file for part in line.split()))

在这里,我们使用 words.get 字典来获取针对单词存储的值,如果在字典中找不到该单词(既不是好词也不是坏词),那么 return默认值 0.