繁体   English   中英

在整个语料库中查找特定单词的有效方法

[英]Efficient way to find specific words in the entire corpus

我必须为语料库中的每个单词构建一个具有术语权重的文档,并且需要执行几个预处理步骤。 其中之一是删除在整个语料库中出现少于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

我的猜测是您的代码在此块中花费了大部分时间:

for k,v in check_dir.items():
    for a,b in new_dir.items():
        if k==a and b==1:
            del temp_dict[k]

还有这个方块

    for k,v in full_dir.items():
        for a,b in temp_dict.items():
            if k == a:
                dnum_list[a] = v

您在这里做了很多不必要的工作。 您一次遍历new_dirtemp_dict一次就足够了。

这两个块可以简化为:

for a, b in new_dir.items():
    if check_dir.get(a) == 1:
        del temp_dict[a]

和:

for a, b in temp_dict.items():
    if a in full_dir:
        dnum_list[a] = v

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM