文本相似在问答系统中有很重要的应用,如基于知识的问答系统(Knowledge-based QA),基于文档的问答系统(Documen-based QA),以及基于FAQ的问答系统(Community-QA)等。像 对于问题的内容,需要进行相似度匹配,从而选择出与问题最接近,同时最合理的答案。本节介绍 基于ngram-tf-idf的余弦距离计算相似度。
本节将介绍两种实现:基于sklearn 和 基于gensim
基于sklearn的方式如下:
import os
import re
import jieba
import pickle
import logging
import numpy as np
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer
class StopWords(object):
'''
'''
def __init__(self, stopwords_file=stopwords_file ):
self.stopwords = set( [ word.strip() for word in open(stopwords_file, 'r') ] )
def del_stopwords(self, words):
return [ word for word in words if word not in self.stopwords ]
stop_word = StopWords()
# gen 3-gram
def _list_3_ngram(words, n=3, m=2):
pattern1 = re.compile(r'[0-9]')
if len(words) < n:
n = len(words)
temp=[words[i - k:i] for k in range(m, n + 1)
了解本专栏
订阅专栏 解锁全文
作者:MachineLP