Java计算TF-IDF值

本文介绍了一种基于Map实现的TF-IDF模型计算方法,详细解释了如何通过遍历文件夹内的文本文件来计算词频(TF)和逆文档频率(IDF),并最终得到每个单词的TF-IDF值。此方法适用于处理大量文档集合,能够有效提取文档中的关键信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在自然语言处理中,TF-IDF模型的计算是一种很基础的方式,在很多地方都会去使用。但是由于TF-IDF的计算一般涉及到的是一个稀疏矩阵的计算,本部分使用Map来完成对TF-IDF的构建。

计算完成后,可以通过类的get方法来对计算所得的TF以及IDF的值。其中
tf格式:( 文件路径名 : ( 单词 : 词频 ) )
idf格式:( 单词 : IDF )


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import files.FileIO;

public class TFIDF
{
    // tf格式:( 文件路径名 : ( 单词 : 词频 ) )
    final private Map<String , HashMap<String, Integer>> tf = new HashMap<>();
    final private Map<String, Integer> df = new HashMap<String, Integer>();
    // idf格式:( 单词 : IDF )
    final private Map<String, Double> idf = new HashMap<String, Double>();

    final private String corpusPath;
    final private String charSet;

    /**
     * 获取计算所得的TF值
     * @return
     */
    public Map<String , HashMap<String, Integer>> getTf()
    {
        return tf;
    }

    /**
     * 获取计算所得的IDF值
     * @return
     */
    public Map<String, Double> getIdf()
    {
        return idf;
    }

    /**
     * 初始化类
     * @param corpusPath 待计算TF-IDF的文件夹
     * @param charSet 文件夹下文件的编码格式
     */
    public TFIDF(String corpusPath , String charSet)
    {
        this.corpusPath = corpusPath;
        this.charSet = charSet;
    }

    /**
     * 计算TF-IDF值
     * @throws IOException
     */
    public void calculate() throws IOException
    {
        int number = 0;
        number = forAllFiles(number , new File(corpusPath));

        for (Entry<String, Integer> entry : df.entrySet())
        {
            idf.put(entry.getKey(), Math.log(1.0 * number / entry.getValue()));
        }

    }

    private int forAllFiles(int number , File path) throws UnsupportedEncodingException,
            FileNotFoundException, IOException
    {
        if(path.isFile())
        {
            number ++;

            String text = FileIO.readFile(path, charSet);
            HashMap<String , Integer> temp = new HashMap<>();
            for (String string : text.split("\\s+"))
            {
                if(temp.containsKey(string))
                {
                    temp.put(string, 1 + temp.get(string));
                }
                else
                {
                    temp.put(string, 1);
                }
            }

            tf.put(path.getAbsolutePath(), temp);

            for (String string : temp.keySet())
            {
                if(df.containsKey(string))
                {
                    df.put(string, 1 + df.get(string));
                }
                else
                {
                    df.put(string, 1);
                }
            }
        }
        else if(path.isDirectory())
        {
            for (File file : path.listFiles())
            {
                number = forAllFiles(number , file);
            }
        }

        return number;
    }

    final public static String readFile(File file, String charset) throws 
            UnsupportedEncodingException, FileNotFoundException, IOException
    {
        StringBuilder re = new StringBuilder();

        String line = "";
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(
                        new FileInputStream(file),
                        charset)))
        {
            while ((line = br.readLine()) != null)
            {
                re.append(line + "\n");
            }
        }
        return re.toString();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值