【发布时间】:2018-09-05 02:32:40
【问题描述】:
我必须为语料库中的每个单词构建一个包含词权重的文档,并且我需要执行几个预处理步骤。其中之一是删除在整个语料库中出现少于 5 次的每个单词。 这就是我所做的,我确信这不是最有效的方法。
假设我有 10 个 HTML 文档。我从每个文档中读取,使用 nltk 和 BeautifulSoup 进行标记,将输出写入文件。我必须首先对所有 10 个文档执行此操作。再次阅读所有 10 个文档以检查特定术语在整个语料库中出现的次数,并将输出写入不同的文件。
由于我要读取和写入每个文件两次(必须为 1000 个文档执行此操作),因此执行程序需要很长时间。 如果有人能提出一种不需要很长时间并且效率更高的替代方法,我将不胜感激。我正在使用 Python3。
谢谢
def remove_words(temp_path):
#####PREPROCESING : Remove words that occur only once in the entire corpus , i.e words with value =1
temp_dict={}
with open(temp_path) as file:
for line in file:
(key,value)=line.split()
temp_dict[key]=value
#print("Lenght before removing words appearing just once: %s"%len(temp_dict))
check_dir=temp_dict.copy()
new_dir=full_dir.copy()
for k,v in check_dir.items(): #Compare each temperary dictionary with items in full_dir. If a match exits and the key value=1, delete it
for a,b in new_dir.items():
if k==a and b==1:
del temp_dict[k]
#print("Length after removing words appearing just once: %s \n"%len(temp_dict))
return temp_dict
def calc_dnum(full_dir,temp_dict):
#Function to calculate the total number of documents each word appears in
dnum_list={}
for k,v in full_dir.items():
for a,b in temp_dict.items():
if k==a:
dnum_list[a]=v
return dnum_list
【问题讨论】:
-
请发布您的代码。通过合理的实现,此设计的运行时间不应超过几秒钟。
-
@Marat ,我已经发布了整个代码!谢谢
标签: python full-text-search information-retrieval