tfidf算法+余弦相似度算法计算文本相似度

TF-IDF(term frequency–inverse document frequency)是一种用于信息检索与数据挖掘的常用加权技术。TF意思是词频(Term Frequency),IDF意思是逆向文件频率(Inverse Document Frequency)。/** * 直接匹配2个文本 * * @author rock * */public class GetText {
摘要由CSDN通过智能技术生成

TF-IDF(term frequency–inverse document frequency)是一种用于信息检索与数据挖掘的常用加权技术。TF意思是词频(Term Frequency),IDF意思是逆向文件频率(Inverse Document Frequency)。

思想:对文本进行分词,然后用tfidf算法得到文本对应的词向量,然后利用余弦算法求相似度
需要的jar :je-analysis-1.5.3.jar ,lucene-core-2.4.1.jar(高于4的版本会有冲突)

/**
 * 直接匹配2个文本
 * 
 * @author rock
 *
 */
public class GetText {
   
    private static List<String> fileList = new ArrayList<String>();
    private static HashMap<String, HashMap<String, Double>> allTheTf = new HashMap<String, HashMap<String, Double>>();
    private static HashMap<String, HashMap<String, Integer>> allTheNormalTF = new HashMap<String, HashMap<String, Integer>>();
    private static LinkedHashMap<String, Double[]> vectorMap = new LinkedHashMap<String, Double[]>();

    /**
     * 分词
     * 
     * @author create by rock
     */
    public static String[] TextcutWord(String text) throws IOException {
        String[] cutWordResult = null;
        MMAnalyzer analyzer = new MMAnalyzer();
        String tempCutWordResult = analyzer.segment(text, " ");
        cutWordResult = tempCutWordResult.split(" ");
        return cutWordResult;
    }

    public static Map<String, HashMap<String, Integer>> NormalTFOfAll(String key1, String key2, String text1,
            String text2) throws IOException {
        if (allTheNormalTF.get(key1) == null) {
            HashMap<String, Integer> dict1 = new HashMap<String, Integer>();
            dict1 = normalTF(TextcutWord(text1));
            allTheNormalTF.put(key1, dict1);
        }
        if (allTheNormalTF.get(key2) == null) {
            HashMap<String, Integer> dict2 = new HashMap<String, Integer>();
            dict2 = normalTF(TextcutWord(text2));
            allTheNormalTF.put(key2, dict2);
        }
        return allTheNormalTF;
    }

    public static Map<String, HashMap<String, Double>> tfOfAll(String key1, String key2, String text1, String text2)
            throws IOException {
            allTheTf.clear();
            HashMap<String, Double> dict1 = new HashMap<String, Double>();
            HashMap<String, Double> dict2 = new HashMap<String, Double>();
            dict1 = tf(TextcutWord(text1));
            dict2 = tf(TextcutWord(text2));
            allTheTf.put(key1, dict1);
            allTheTf.put(key2, dict2);
            return allTheTf;
    }

    /**
     * 计算词频
     * 
     * @author create by rock
     */
    public static HashMap<String, Double> tf(String[] cutWordResult) {
        HashMap<String, Double> tf = new HashMap<String, Double>();// 正规化
        int wordNum = cutWordResult.length;
        int wordtf = 0;
        for (int i = 0; i < wordNum; i++) {
            wordtf = 0;
            if (cutWordResult[i] != " ") {
                for (int j = 0; j < wordNum; j++) {
                    if (i != j) {
                        if (cutWordResult[i].equals(cutWordResult[j])) {
                            cutWordResult[j] = " ";
                            wordtf++;
                        }
                    }
                }
                tf.put(cutWordResult[i], (new Double(++wordtf)) / wordNum);
                cutWordResult[i] = 
  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
Python中的文本相似度可以通过基于TF-IDF和余弦相似算法来实现。TF-IDF(Term Frequency-Inverse Document Frequency)是用于评估一个词语在一个文档中的重要程度的方法。 首先,我们需要使用Python中的文本处理库(如nltk)来对文本进行预处理,包括分词、去除停用词、词干化等。接下来,我们可以使用sklearn库中的TF-IDF向量化器来将文本转换为TF-IDF特征向量。 然后,我们可以使用余弦相似算法计算两个文本之间的相似度。余弦相似度是通过计算两个向量之间的夹角来度量它们的相似程度的。 以下是一个简单的示例代码: ```python import nltk from nltk.corpus import stopwords from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity def preprocess_text(text): # 分词 tokens = nltk.word_tokenize(text) # 去除停用词 stop_words = set(stopwords.words('english')) tokens = [token for token in tokens if token.lower() not in stop_words] # 词干化 stemmer = nltk.PorterStemmer() tokens = [stemmer.stem(token) for token in tokens] # 返回处理后的文本 return " ".join(tokens) def calculate_similarity(text1, text2): # 预处理文本 processed_text1 = preprocess_text(text1) processed_text2 = preprocess_text(text2) # 转换为TF-IDF特征向量 vectorizer = TfidfVectorizer() tfidf_matrix = vectorizer.fit_transform([processed_text1, processed_text2]) # 计算余弦相似度 cosine_sim = cosine_similarity(tfidf_matrix[0], tfidf_matrix[1]) # 返回相似度 return cosine_sim[0][0] text1 = "今天天气不错" text2 = "今天天气很好" similarity = calculate_similarity(text1, text2) print("文本1和文本2的相似度为:", similarity) ``` 在以上示例中,我们先对文本进行了预处理,并使用TF-IDF向量化器将其转换为特征向量。然后,我们使用余弦相似算法计算文本1和文本2之间的相似度,并输出结果。 这只是一个简单的示例,实际应用中可能需要更多的预处理步骤和参数调整来获得更好的结果。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值