【问题标题】:Efficient way to find specific words in the entire corpus在整个语料库中查找特定单词的有效方法
【发布时间】: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


【解决方案1】:

我的猜测是你的代码大部分时间都花在这个块上:

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

【讨论】:

  • 非常感谢@myrtlecat。这显着提高了执行速度。 500 个文件大约需要 45 秒。我刚开始学习 Python,如果您有任何改进程序的建议,我将不胜感激 - 无论是速度还是编码风格。
猜你喜欢
  • 2020-10-28
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 2020-12-09
  • 1970-01-01
  • 2021-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多