python - 检查文本文件中的单词是否存在于第二个文本文件中太慢了
问题描述
我有一个文本文件,我试图找出该文本文件中的所有单词是否都存在于词典或“字典”中。如果有一个词不在字典中,则输出应该是该词以及它出现的次数。
该代码适用于小型文本文件,但不适用于大型文本文件。无法判断它是否崩溃或是否仍在工作。
我正在使用 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))
解决方案
- 您的词典应该在 a 中
set
,而不是 alist
中,以便您可以在恒定时间而不是线性时间中检查单词的存在。 - 您可以在读取文件时直接建立您的缺失计数器,而不是将整个内容加载到内存中并制作一个缺失单词的临时列表。
因此:
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
推荐阅读
- wix - 如何在升级时跳过 InstallDir 对话框
- python - 从单独的函数检查 python 线程的状态
- java - 想实现并行/并发读取文件
- sql - 我想运行一个嵌套查询,首先执行左连接,然后提取最近 3 个月的 Volume >= 2 和 Date 的数据
- javascript - 在 Nodejs 中使用密码对字符串进行编码的简单方法?
- casting - 如何将对象转换为 FSharp 列表
- linux - 如何在bash中比较2个文件并替换file2中匹配行的单词?
- c# - .NET Core Web API / Angular 应用程序中的 Windows 身份验证
- intellij-idea - 如何在 IntelliJ IDEA 的调试器中通过引用来观察特定的 Java 对象?
- python - 点击功能不适用于投票元素