首页 > 解决方案 > 检查文本文件中的单词是否存在于第二个文本文件中太慢了

问题描述

我有一个文本文件,我试图找出该文本文件中的所有单词是否都存在于词典或“字典”中。如果有一个词不在字典中,则输出应该是该词以及它出现的次数。

该代码适用于小型文本文件,但不适用于大型文本文件。无法判断它是否崩溃或是否仍在工作。

我正在使用 Python 3

import os
import argparse
from collections import Counter


def countoov(lexicon,text):
    lexicon_list = []
    oov = []
    word_list = []
    with open(lexicon,"r",encoding="utf-8") as lf:
        lines = lf.readlines()
    for line in lines:
        line = line.strip()
        lexicon_list.append(line)
    #print(lexicon_list)
    #import pdb; pdb.set_trace()            
    
    with open(text,"r",encoding="utf-8") as tf:
        lines = tf.readlines()    
    for line in lines:
        line = line.strip().split()
        word_list.extend(line)
        #count = 0
        #Problem here
        #for word in line:
        #    if word not in lexicon_list:
        #        oov.append(word)
    for word in word_list:
        if word not in lexicon_list:
            oov.append(word)
    
    counter = Counter(oov)

    return counter

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--textfile', type=str, required=True, help='input directory of train text')
    parser.add_argument('--lexicon',type=str, required=True, help='input directory of lexicon')
    args = parser.parse_args()

    print(countoov(args.lexicon, args.textfile))

标签: pythonpython-3.x

解决方案


  1. 您的词典应该在 a 中set,而不是 alist中,以便您可以在恒定时间而不是线性时间中检查单词的存在。
  2. 您可以在读取文件时直接建立您的缺失计数器,而不是将整个内容加载到内存中并制作一个缺失单词的临时列表。

因此:

def count_missing(lexicon, text):
    words = set()
    with open(lexicon) as lf:
        for line in lf:  # Assuming one word per line in the lexicon
            words.add(line.strip())
    missing = Counter()
    with open(text) as tf:
        for line in tf:
            for word in line.split():
                if word not in words:
                    missing[word] += 1
    return missing

推荐阅读