0


使用Python过滤出类似的文本的简单方法

问题

假设在存档中有成千上万的文档,其中许多是彼此重复的,即使文档的内容相同,标题不同。现在想象一下,现在老板要求你通过删除不必要的重复文档来释放一些空间。

问题是:如何过滤标题足够相似的文本,以使内容可能相同?接下来,如何实现此目标,以便在完成操作时不会删除过多的文档,而保留一组唯一的文档?让我们用一些代码使它更清楚:

titles = [
    "End of Year Review 2020",
    "2020 End of Year",
    "January Sales Projections",
    "Accounts 2017-2018",
    "Jan Sales Predictions"
]

# Desired output
filtered_titles = [
    "End of Year Review 2020",
    "January Sales Projections",
    "Accounts 2017-2018",
]

根据以上的问题,本文适合那些希望快速而实用地概述如何解决这样的问题并广泛了解他们同时在做什么的人!

接下来,我将介绍我为解决这个问题所采取的不同步骤。下面是控制流的概要:

预处理所有标题文本

生成所有标题成对

测试所有对的相似性

如果一对文本未能通过相似性测试,则删除其中一个文本并创建一个新的文本列表

继续测试这个新的相似的文本列表,直到没有类似的文本留下

用Python表示,这可以很好地映射到递归函数上!

代码

下面是Python中实现此功能的两个函数。

importspacy
fromitertoolsimportcombinations

# Set globals
nlp = spacy.load("en_core_web_md")

defpre_process(titles):
    """
    Pre-processes titles by removing stopwords and lemmatizing text.
    :param titles: list of strings, contains target titles,.
    :return: preprocessed_title_docs, list containing pre-processed titles.
    """

    # Preprocess all the titles
    title_docs = [nlp(x) forxintitles]
    preprocessed_title_docs = []
    lemmatized_tokens = []
    fortitle_docintitle_docs:
        fortokenintitle_doc:
            ifnottoken.is_stop:
                lemmatized_tokens.append(token.lemma_)
        preprocessed_title_docs.append(" ".join(lemmatized_tokens))
        dellemmatized_tokens[
            :
            ]  # empty the lemmatized tokens list as the code moves onto a new title

    returnpreprocessed_title_docs

defsimilarity_filter(titles):
    """
    Recursively check if titles pass a similarity filter.
    :param titles: list of strings, contains titles.
    If the function finds titles that fail the similarity test, the above param will be the function output.
    :return: this method upon itself unless there are no similar titles; in that case the feed that was passed
    in is returned.
    """

    # Preprocess titles
    preprocessed_title_docs = pre_process(titles)

    # Remove similar titles
    all_summary_pairs = list(combinations(preprocessed_title_docs, 2))
    similar_titles = []
    forpairinall_summary_pairs:
        title1 = nlp(pair[0])
        title2 = nlp(pair[1])
        similarity = title1.similarity(title2)
        ifsimilarity>0.8:
            similar_titles.append(pair)

    titles_to_remove = []
    fora_titleinsimilar_titles:
        # Get the index of the first title in the pair
        index_for_removal = preprocessed_title_docs.index(a_title[0])
        titles_to_remove.append(index_for_removal)

    # Get indices of similar titles and remove them
    similar_title_counts = set(titles_to_remove)
    similar_titles = [
        x[1] forxinenumerate(titles) ifx[0] insimilar_title_counts
    ]

    # Exit the recursion if there are no longer any similar titles
    iflen(similar_title_counts) == 0:
        returntitles

    # Continue the recursion if there are still titles to remove
    else:
        # Remove similar titles from the next input
        fortitleinsimilar_titles:
            idx = titles.index(title)
            titles.pop(idx)
            
        returnsimilarity_filter(titles)

if__name__ == "__main__":
    your_title_list = ['title1', 'title2']
    similarty_filter(your_title_list)

第一个是预处理标题文本的简单函数;它删除像' the ', ' a ', ' and '这样的停止词,并只返回标题中单词的引理。

如果你在这个函数中输入“End of Year Review 2020”,你会得到“end year review 2020”作为输出;如果你输入“January Sales Projections”,你会得到“january sale projection”。

它主要使用了python中非常容易使用的spacy库.

第二个函数(第30行)为所有标题创建配对,然后确定它们是否通过了余弦相似度测试。如果它没有找到任何相似的标题,那么它将输出一个不相似标题的列表。但如果它确实找到了相似的标题,在删除没有通过相似度测试的配对后,它会将这些过滤后的标题再次发送给它自己,并检查是否还有相似的标题。

这就是为什么它是递归的!简单明了,这意味着函数将继续检查输出,以真正确保在返回“最终”输出之前没有类似的标题。

什么是余弦相似度?

但简而言之,这就是spacy在幕后做的事情……

首先,还记得那些预处理过的工作吗?首先,spacy把我们输入的单词变成了一个数字矩阵。

一旦它完成了,你就可以把这些数字变成向量,也就是说你可以把它们画在图上。

一旦你这样做了,计算两条直线夹角的余弦就能让你知道它们是否指向相同的方向。

所以,在上图中,想象一下,A线代表“闪亮的橙色水果”,B线代表“闪亮的红苹果是一种水果”。

在这种情况下,行A和行B都对应于空格为这两个句子创建的数字矩阵。这两条线之间的角度——在上面的图表中由希腊字母theta表示——是非常有用的!你可以计算余弦来判断这两条线是否指向同一个方向。

这听起来似乎是显而易见的,难以计算,但关键是,这种方法为我们提供了一种自动化整个过程的方法。

总结

回顾一下,我已经解释了递归python函数如何使用余弦相似性和spacy自然语言处理库来接受相似文本的输入,然后返回彼此不太相似的文本。

可能有很多这样的用例……类似于我在本文开头提到的归档用例,可以使用这种方法在数据集中过滤具有惟一歌词的歌曲,甚至过滤具有惟一内容类型的社交媒体帖子。

作者:osintalex

原文地址:https://towardsdatascience.com/how-to-filter-out-similar-texts-in-python-c7e7c5f7620e

deephub翻译组

标签:

“使用Python过滤出类似的文本的简单方法”的评论:

还没有评论