SimilarVocabulary--动手实现一个基于NLP的相近单词检索器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wang7807564/article/details/82859570

介绍

SimilarVocabulary是我在github上的一个开源项目,项目本身并不复杂,使用了NLP中的词向量来检索到关联程度较大的单词,项目套用了NLP中一个开源的库spacy.该库自带了一个训练好的模型,可以进行英文文本的预测。
项目地址:

https://github.com/wotchin/SimilarVocabulary

代码细节

下面,我们以这个简单的demo演示一下spacy库的使用,以及介绍获取相近单词的代码。

加载模型

nlp = spacy.load('en_core_web_lg')

其中,en_core_web_log 是该库自带的一个训练好的模型,这个模型很大,需要自己下载,我在这里给出了初始化的脚本为:init.sh

获取输入文本

这行代码主要是用于获取输入文本内容,然后将输入的文本(主要是单词)进行预处理,生成token:

    while True:
        if line != "":
            words += line.replace("\n"," ")
            line = f.read()
        else:
            break

    nlp = spacy.load('en_core_web_lg')
    print("modal loaded.")
    tokens = nlp(words)

设定阈值

套用这个库来实现相近单词检索的大致原理是:
通过已经训练好的模型,通过词向量对比给定的两个单词之间的“距离”,我们给定的这个阈值就是这个“距离”的上线,通过设定这个上限值,就可以获取我们想要的输出结果——语义相近的单词。
我们简单看一下设定阈值的过程:

threshold = 0.0
    while threshold <= 0.0:
        try:
            threshold = float(input("input threshold value:"))
        except:
            threshold = 0.0

    length = 3
    try:
        length = int(input("input result length:"))
    except:
        length = 3

代码很简单:要求输入阈值,需要查询到的相近单词的个数。

实现对比查询

我在这里实现的逻辑是:给一个语料库数据集,数据集里收集了绝大多数的常用英文单词,在这个数据集中寻找与我们事先给定的单词意思相近的结果,然后选择n个比较优的结果返回。这部分的代码是:

  while True:
        queue = [] #[['dog',0.1],['cat',0.2]...]
        i = input("input your word:")
        if i != "":
            txt = nlp(i)
            for token in tokens:
                score = token.similarity(txt)
                if score >= threshold and family_check(txt.text.strip(),token.text.strip()) < 0:
                    if len(queue) >= length:
                        index = 0 # in order to contrast 
                        value = 1.0
                        for i in range(0,len(queue)):
                            if queue[i][1] < value:
                                value = queue[i][1]
                                index = i
                        if value < score:
                            queue[index] = [token.text,score]

                    else:
                        queue.append([token.text,score])

        print(queue)

用途

诸如这样寻找相似的单词的意义是怎样的呢? 譬如某些答题竞猜类APP,如之前非常火爆的在线直播答题类APP进行编题时,如果只有一个选项,需要补充额外三个干扰选项怎么办?可以使用这样的相近单词生成器,生成关联比较近的单词,例如输入单词dog,它可能会为我们返回:pig,cat,cook.当然了,它的更多用途不止于此,全凭脑洞。

猜你喜欢

转载自blog.csdn.net/wang7807564/article/details/82859570