您的位置:首页 > 编程语言 > Java开发

Java计算TF-IDF值

2016-03-11 15:05 387 查看
在自然语言处理中,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();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息